Skip to content

Instantly share code, notes, and snippets.

@juanbrusco
Created October 11, 2018 20:48
Show Gist options
  • Save juanbrusco/6c0bf51c27b404563eb6e6a5abea8b18 to your computer and use it in GitHub Desktop.
Save juanbrusco/6c0bf51c27b404563eb6e6a5abea8b18 to your computer and use it in GitHub Desktop.
Get JSON from url - Java
public static void main(String[] args) {
HttpURLConnection connection = null;
String inputLine;
StringBuffer response = new StringBuffer();
try {
URL url = new URL("url");
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Content-Type","application/json");
connection.setUseCaches(false);
connection.setDoOutput(true);
if (connection.getResponseCode()==200) {
BufferedReader in = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
JSONObject obj = new JSONObject(response.toString());
System.out.println(obj);
}
else {
System.out.println("Can't get data");
}
} catch (IOException e) {
e.printStackTrace();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment