4

我现在正在尝试使用 Java 线中的 HTTP 请求来获取 JSON 对象。

我想知道如何在以下线路中获取响应或 JSON 对象。

请告诉我。

(在这个程序中,我尝试获取文章“纽约”的维基百科类别。)

 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);
4

4 回答 4

4

只需 2 行代码JSONTokener

JSONTokener tokener = new JSONTokener(wikiRequest.openStream());
JSONObject root = new JSONObject(tokener);
于 2016-03-27T13:55:06.093 回答
2
Scanner scanner = new Scanner(wikiRequest.openStream());
String response = scanner.useDelimiter("\\Z").next();
JSONObject json = Util.parseJson(response);
scanner.close();
于 2012-08-10T12:48:31.510 回答
0

如果您使用的是 URLConnection,您应该能够读取流而不是获取响应对象:

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

请参阅:http ://docs.oracle.com/javase/tutorial/networking/urls/readingWriting.html

于 2012-08-10T12:44:15.750 回答
0

使用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>
于 2013-05-19T22:40:51.407 回答