簡體   English   中英

Java - 從 URL 獲取 JSON 數據

[英]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。

  • 如果您使用的是 Java 11,則可以在內置的 web 客戶端中使用 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();

  • 使用 OkHttp 之類的庫,您必須創建一個請求並將其提供給 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())

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM