Reputation: 31
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
Reputation: 11
There are multiple options to get a json in java.
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();
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
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