get json from url java code example
Example 1: how to read a .json from web api java
try {
URL url = new URL("url");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("GET");
conn.connect();
if(conn.getResponseCode() == 200) {
Scanner scan = new Scanner(url.openStream());
while(scan.hasNext()) {
String temp = scan.nextLine();
}
}
}
Example 2: java get json from url
try(BufferedReader br=new BufferedReader(new InputStreamReader(new URL("URL here").openStream()))){
JSONObject json=new JSONObject(br.lines().collect(Collectors.joining()));
json.getString("hello");
json.getInt("world");
json.getJSONObject("test");
json.getJSONObject("test").getString("something");
}