Repository navigation
Expand file tree
/
Copy pathHttpJSONReader.java
More file actions
89 lines (79 loc) · 3.16 KB
/
Copy pathHttpJSONReader.java
File metadata and controls
89 lines (79 loc) · 3.16 KB
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package org.json.util;
/************************************************************************************************
* *
* This class contains static methods for reading and parsing http json response *
* *
* *
* *
* Copyright Gamal Shaban 2012. *
* gemy21ce@gmail.com *
* *
* *
* *
* *
************************************************************************************************/
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import org.json.JSONException;
import org.json.JSONObject;
/**
* This provides reading json from http response,parse it into json object.
*
* @author Gamal Shaban
*/
public final class HttpJSONReader {
/**
* read from the Reader object.
*
* @param rd
* @return
* @throws IOException
*/
protected static String readAll(Reader rd) throws IOException {
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
return sb.toString();
}
/**
* read the url and passes the response as String.
*
* @param url
* @return
*/
public static String readOnly(String url) throws MalformedURLException, IOException {
InputStream is = new URL(url).openStream();
//surround the statments with try and finally so make sure that inputstream will be closed.
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String jsonText = readAll(rd);
return jsonText;
} finally {
is.close();
}
}
/**
* reads the url and passes the response as json object.
*
* @param url
* @return
*/
public static JSONObject readAndParse(String url) throws JSONException, MalformedURLException, IOException {
//call the readOnly method and parse the json.
JSONObject json = new JSONObject(readOnly(url));
return json;
}
/**
* parse a json string and returns the json object representation.
*
* @param jsonString
* @return
*/
public static JSONObject parse(String jsonString) throws JSONException {
return new JSONObject(jsonString);
}
}