-
Notifications
You must be signed in to change notification settings - Fork 4
/
TestJsonPost.java
67 lines (55 loc) · 2.01 KB
/
TestJsonPost.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package org.vishal.tester;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
public class TestJsonPost {
public static void main(String args[]){
try {
JSONObject json = readJsonFromUrl("http://localhost:7777/JAXRSJsonExample1/rest/countries");
JSONArray array=(JSONArray) json.get("array");
System.out.println("size "+array.length());
for(int i=0;i<array.length();i++)
{
JSONObject object=(JSONObject) array.get(i);
System.out.println(object.get("id")+" "+object.get("countryName")+" "+object.get("population"));
}
} catch (IOException | JSONException e) {
e.printStackTrace();
}
}
private static String readAll(Reader rd)throws IOException{
StringBuilder sb=new StringBuilder();
int cp;
while((cp=rd.read())!= -1){
sb.append((char)cp);
}
String newString="{"+"array:"+sb.toString()+"}";
return newString;
}
public static JSONObject readJsonFromUrl(String url)throws IOException, JSONException{
URL url1 = new URL(url);
HttpURLConnection con= (HttpURLConnection)url1.openConnection();
con.setRequestMethod("GET");
con.connect();
int responsecode= con.getResponseCode();
if(responsecode !=200)
throw new RuntimeException("HttResponseCodeException "+responsecode );
else{ InputStream is= con.getInputStream();
try {
BufferedReader rd= new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String jsontext= readAll(rd);
JSONObject jsonobj=new JSONObject(jsontext);
return jsonobj;
} finally{
is.close();
}
}}
}