[英]Java - get JSON data from URL
我正在尝试从http://api.conceptnet.io/c/en/concept中提取 JSON 文档,但我没有成功将 Z0ECD11C1D7A287401D148A23BBD7A2 数据放入变量中。 我所做的就是获取页面的源代码(特别是第一行,但我理解为什么我只得到一行):
InputStream stream = url.openStream();
Scanner scan = new Scanner(stream);
String data = scan.nextLine();
System.out.println(data);
这没有帮助。 如果我可以将 JSON 数据转换为字符串,我可以将其输入到 JSONObject 构造函数中以构建 JSONObject。 如果我在 python 中这样做,我所要做的就是:
concept = requests.get('http://api.conceptnet.io/c/en/' + theword).json()
但我无法在 Java 中找出等价物。 我对 web 请求的经验很少,所以我很感激任何帮助。
然而 pythonic 方式似乎更容易,在 Java 中没有比这更容易的了。
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
不要忘记在下面添加依赖项。
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;
org.json
的依赖关系可以在这里找到: https://mvnrepository.com/artifact/org.json/json
有多种选择可以在 java 中获得 json。
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())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.