Robobot1747
Robobot1747

Reputation: 31

Java - get JSON data from URL

I'm trying to pull a JSON document from http://api.conceptnet.io/c/en/concept but I haven't been successful in getting the JSON data into a variable. All I've managed to do is to get the page's source (specifically just the first line, but I understand why I only get one line) with:

InputStream stream = url.openStream();
Scanner scan = new Scanner(stream);
String data = scan.nextLine();
System.out.println(data);

Which isn't helpful. If I could get the JSON data into a String, I can feed that into a JSONObject constructor to build the JSONObject. If I were doing this in python, all I would have to do is:

concept = requests.get('http://api.conceptnet.io/c/en/' + theword).json()

But I can't figure out the equivalent for that in Java. I have very little experience with web requests so I appreciate any help.

Upvotes: 3

Views: 8069

Answers (2)

jøkęr
jøkęr

Reputation: 11

There are multiple options to get a json in java.

  • If you are using Java 11, you can use Java in built web client.

    HttpClient client = HttpClient.newHttpClient();
    HttpRequest request = HttpRequest.newBuilder()
      .uri(URI.create("http://api.conceptnet.io/c/en/concept"))
      .build();
    client.sendAsync(request, BodyHandlers.ofString())
      .thenApply(HttpResponse::body)
      .thenAccept(System.out::println)
      .join();

  • Using a library like OkHttp, you have to create a request and feed it to the HttpClient.

    Request request = new Request
       .Builder()
       .url("http://api.conceptnet.io/c/en/concept")
       .get()
       .build()

    OkHttpClient httpClient = client.newBuilder().build()
    Response response = httpClient.newCall(request).execute()
    System.out.println(response.body.string())

Upvotes: 1

sameera sy
sameera sy

Reputation: 1718

However pythonic way seems much easier, it can't get more easy in Java than this.

HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder().uri(URI.create("http://api.conceptnet.io/c/en/concept")).build();

HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
JSONObject myObject = new JSONObject(response.body());
System.out.println(myObject); // Your json object

Don't forget to add the dependencies below.

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import org.json.JSONObject;

Dependency for org.json can be found here : https://mvnrepository.com/artifact/org.json/json

Upvotes: 0

Related Questions