Skip to content

Instantly share code, notes, and snippets.

@snetts
Forked from zvineyard/json_class.java
Created April 30, 2014 16:47
Show Gist options
  • Save snetts/3dd31cf932939b57fdfb to your computer and use it in GitHub Desktop.
Save snetts/3dd31cf932939b57fdfb to your computer and use it in GitHub Desktop.
public class Json {
public static JSONObject getJson(String url){
InputStream is = null;
String result = "";
JSONObject jsonObject = null;
// HTTP
try {
HttpClient httpclient = new DefaultHttpClient(); // for port 80 requests!
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch(Exception e) {
return null;
}
// Read response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"utf-8"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch(Exception e) {
return null;
}
// Convert string to object
try {
jsonObject = new JSONObject(result);
} catch(JSONException e) {
return null;
}
return jsonObject;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment