| 1 | package jsonexample; |
|---|
| 2 | |
|---|
| 3 | import java.util.HashMap; |
|---|
| 4 | import java.util.Map; |
|---|
| 5 | import java.io.BufferedReader; |
|---|
| 6 | import java.io.InputStream; |
|---|
| 7 | import java.io.InputStreamReader; |
|---|
| 8 | import java.net.Authenticator; |
|---|
| 9 | import java.net.PasswordAuthentication; |
|---|
| 10 | import java.net.URL; |
|---|
| 11 | import java.util.Set; |
|---|
| 12 | import org.json.*; |
|---|
| 13 | |
|---|
| 14 | /** |
|---|
| 15 | * @author Vojtech Kovar, xkovar3@fi.muni.cz |
|---|
| 16 | */ |
|---|
| 17 | |
|---|
| 18 | public class Main { |
|---|
| 19 | |
|---|
| 20 | public Main() { |
|---|
| 21 | } |
|---|
| 22 | |
|---|
| 23 | public static void main(String[] args) { |
|---|
| 24 | String data, url_string; |
|---|
| 25 | String base_url = "http://localhost/auth/run.cgi/"; |
|---|
| 26 | String method = "wordlist"; |
|---|
| 27 | Map attrs; |
|---|
| 28 | JSONObject json_query; |
|---|
| 29 | |
|---|
| 30 | final String usr = "<username>"; |
|---|
| 31 | final String passwd = "<password>"; |
|---|
| 32 | |
|---|
| 33 | // authentication issues |
|---|
| 34 | Authenticator auth = new Authenticator() { |
|---|
| 35 | protected PasswordAuthentication getPasswordAuthentication () { |
|---|
| 36 | return new PasswordAuthentication(usr, passwd.toCharArray()); |
|---|
| 37 | } |
|---|
| 38 | }; |
|---|
| 39 | Authenticator.setDefault(auth); |
|---|
| 40 | |
|---|
| 41 | // creating query string |
|---|
| 42 | attrs = new HashMap(); |
|---|
| 43 | attrs.put("corpname", "bnc"); |
|---|
| 44 | attrs.put("wlattr", "word"); |
|---|
| 45 | attrs.put("wlpat", "test.*"); |
|---|
| 46 | attrs.put("format", "json"); |
|---|
| 47 | json_query = new JSONObject(attrs); |
|---|
| 48 | url_string = base_url + method + "?json=" + json_query.toString(); |
|---|
| 49 | |
|---|
| 50 | try { |
|---|
| 51 | // connecting the SketchEngine Server |
|---|
| 52 | URL url = new URL(url_string); |
|---|
| 53 | InputStream stream = url.openStream(); |
|---|
| 54 | InputStreamReader isr = new InputStreamReader(stream); |
|---|
| 55 | BufferedReader reader = new BufferedReader(isr); |
|---|
| 56 | |
|---|
| 57 | // json data receiving |
|---|
| 58 | data = reader.readLine(); // json data are on the first line |
|---|
| 59 | |
|---|
| 60 | // now, in the 'data' variable, there is a json string |
|---|
| 61 | // that can be parsed for json syntax |
|---|
| 62 | JSONObject json = new JSONObject(data); |
|---|
| 63 | System.out.println(json.toString(3)); |
|---|
| 64 | } |
|---|
| 65 | catch(Exception e) { |
|---|
| 66 | e.printStackTrace(); |
|---|
| 67 | } |
|---|
| 68 | } |
|---|
| 69 | |
|---|
| 70 | } |
|---|