Skip to content

Instantly share code, notes, and snippets.

@codemilli
Last active January 30, 2016 12:17
Show Gist options
  • Save codemilli/1c6ec0b910dfd9294481 to your computer and use it in GitHub Desktop.
Save codemilli/1c6ec0b910dfd9294481 to your computer and use it in GitHub Desktop.
Get json data over network in Java
public JSONObject GET (String url) {
JSONObject json;
try {
URL target = new URL(url);
HttpURLConnection urlcon = (HttpURLConnection) target.openConnection();
InputStream in = new BufferedInputStream(urlcon.getInputStream());
BufferedReader streamReader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
StringBuilder responseStrBuilder = new StringBuilder();
String inputStr;
while ((inputStr = streamReader.readLine()) != null)
responseStrBuilder.append(inputStr);
json = new JSONObject(responseStrBuilder.toString());
} catch (MalformedURLException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
} catch (JSONException e) {
e.printStackTrace();
return null;
}
return json;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment