SkE/Methods/example: example1.java

File example1.java, 1.7 KB (added by husak, 6 months ago)
Line 
1package jsonexample;
2
3import java.io.BufferedReader;
4import java.io.InputStream;
5import java.io.InputStreamReader;
6import java.net.Authenticator;
7import java.net.PasswordAuthentication;
8import java.net.URL;
9import org.json.*;
10
11public class Main {
12   
13    public Main() {
14    }
15   
16    public static void main(String[] args) {
17        String data;
18           
19            // url with the query
20        String url_string = "http://localhost/auth/run.cgi/wordlist?corpname=bnc;wlattr=word;wlminfreq=5;wlmaxitems=100;wlpat=test.*;format=json";
21
22        final String usr = "<username>";
23        final String passwd = "<password>";
24       
25            // authentication issues
26        Authenticator auth = new Authenticator() {
27            protected PasswordAuthentication  getPasswordAuthentication () {
28                return new PasswordAuthentication(usr, passwd.toCharArray());
29            }
30        };
31        Authenticator.setDefault(auth);
32       
33        try {
34                // connecting the SketchEngine Server
35            URL url = new URL(url_string);
36            InputStream stream = url.openStream();
37            InputStreamReader isr = new InputStreamReader(stream);
38            BufferedReader reader = new BufferedReader(isr);
39           
40                // json data receiving
41            data = reader.readLine(); // json data are on the first line
42           
43                // now, in the 'data' variable, there is a json string
44                // that can be parsed for json syntax
45            JSONObject json = new JSONObject(data);
46            System.out.println(json.toString(3));
47        } 
48        catch(Exception e) {
49            e.printStackTrace();
50        }
51    } 
52}