blob: 47e25ea0a9824dac81cb8e9fc505b1fb34569969 (
plain)
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
|
package org.linaro.connect;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import android.util.Log;
public class JSONUtils {
private final static String TAG = LinaroConnectActivity.TAG;
/**
* Parses the given input stream into a JSON object. This function
* also takes care of closing the input stream
*/
public static JSONObject getObject(InputStream is) {
StringBuffer sb = new StringBuffer();
BufferedReader br = new BufferedReader(new InputStreamReader(is), 1024);
try {
char buff[] = new char[1024];
int len;
while ( (len=br.read(buff)) > 0 )
sb.append(buff, 0, len);
}
catch(IOException e) {
Log.e(TAG, "Unable to read JSON layout", e);
}
try {
is.close();
} catch (IOException e) {}
return toJSON(sb.toString());
}
public static JSONObject getObjectFromUrl(String url) {
HttpClient client = new DefaultHttpClient();
InputStream is = null;
try {
HttpResponse resp = client.execute(new HttpGet(url));
if (resp.getStatusLine().getStatusCode() == 200) {
is = resp.getEntity().getContent();
} else {
Log.e(TAG, "Error fetching URL: " + url);
}
}
catch(Exception e) {
Log.e(TAG, "Exception while fetching URL: " + url, e);
}
if (is == null) //just give an empty object
return toJSON("{}");
return getObject(is);
}
public static JSONObject toJSON(String json) {
try {
return (JSONObject) new JSONTokener(json).nextValue();
} catch(JSONException e) {
Log.e(TAG, "Unable to convert string to JSON", e);
}
return null;
}
}
|