Hanan Saeed
Hanan Saeed

Reputation: 23

how i get JSON as string from url (java)

I want to save this JSON in url { https://www.instagram.com/ihanan95/?__a=1 } and save it as string by java I try used all suggestions but when do it I get empty string.

Upvotes: 1

Views: 10325

Answers (2)

ooozguuur
ooozguuur

Reputation: 3466

Read JSON file from remote website.

Example:

URL url = new URL("https://www.instagram.com/ihanan95/?__a=1");
JSONTokener tokener = new JSONTokener(url.openStream());
JSONObject obj = new JSONObject(tokener);
JSONObject data = obj.getJSONObject("user");
String message = data.getString("message");

JSONTokener Doc

Dependencies

<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20090211</version>
</dependency>

Upvotes: 2

Darshan Mehta
Darshan Mehta

Reputation: 30809

You can use Spring's RestTemplate to get the response as String, e.g.:

RestTemplate restTemplate = new RestTemplate();
String response = restTemplate.getForObject("https://www.instagram.com/ihanan95/?__a=1", String.class);
System.out.println(response);

If you are not allowed to use third party libaries then you can do the same with URLConnection, e.g.:

URLConnection connection = new URL("https://www.instagram.com/ihanan95/?__a=1").openConnection();
try(Scanner scanner = new Scanner(connection.getInputStream());){
    String response = scanner.useDelimiter("\\A").next();
    System.out.println(response);
}

Upvotes: 2

Related Questions