Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Java: Get JSON from URL (Android)
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;
}
}
@gourneau

This comment has been minimized.

Copy link

gourneau commented Sep 20, 2013

This should be using HttpGet instead of HttpPost

@tomlins

This comment has been minimized.

Copy link

tomlins commented Nov 14, 2013

Nice. I added some HttpConnectionParams to set the time outs on the socket and connection to allow more control.

@tulundgren

This comment has been minimized.

Copy link

tulundgren commented Sep 11, 2014

He didnt try the code even once. holy goodness.

@MichalKalita

This comment has been minimized.

Copy link

MichalKalita commented Dec 20, 2017

I don't have a class HttpClient, it was removed in Android 6

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.