簡體   English   中英

如何從Java中的HTTP請求獲取JSON對象

[英]How to get JSON object from HTTP request in Java

我現在正在嘗試使用Java Cord中的HTTP請求獲取JSON對象。

我想知道如何在下面的代碼中獲取響應或JSON對象。

請告訴我。

(在此程序中,我嘗試獲取文章“ New York”的Wikipedia類別。)

 String requestURL = "http://en.wikipedia.org/w/api.php?action=query&prop=categories&format=json&clshow=!hidden&cllimit=10&titles=" + words[i];
 URL wikiRequest = new URL(requestURL);
 URLConnection connection = wikiRequest.openConnection();  
 connection.setDoOutput(true);  

                    /**** I'd like to get response here. ****/

 JSONObject json = Util.parseJson(response);

JSONTokener僅2行代碼

JSONTokener tokener = new JSONTokener(wikiRequest.openStream());
JSONObject root = new JSONObject(tokener);
Scanner scanner = new Scanner(wikiRequest.openStream());
String response = scanner.useDelimiter("\\Z").next();
JSONObject json = Util.parseJson(response);
scanner.close();

如果您使用的是URLConnection,則應該能夠讀取流而不是獲取響應對象:

BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));

請參閱: http : //docs.oracle.com/javase/tutorial/networking/urls/readingWriting.html

使用corn-httpclient和corn-converter的示例實現

HttpClient client = new HttpClient(new URI(http://en.wikipedia.org/w/api.php?action=query&prop=categories&format=json&clshow=!hidden&cllimit=10&titles=" + words[i]));
HttpResponse response = client.sendData(HTTP_METHOD.GET);
if (! response.hasError()) {
String jsonString = response.getData();
JsTypeComplex jsonResponse =  (JsTypeComplex) JsonStringParser.parseJsonString(jsonString);
JsTypeList resultsArr = (JsTypeList) jsonResponse.get("results");

Maven依賴項:

<dependency>
    <groupId>net.sf.corn</groupId>
    <artifactId>corn-httpclient</artifactId>
    <version>1.0.0</version>
</dependency>
<dependency>
    <groupId>net.sf.corn</groupId>
    <artifactId>corn-converter</artifactId>
    <version>1.0.0</version>
</dependency>

暫無
暫無

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

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