如何从Java中的HTTP请求中获取JSON对象

时间:2012-08-10 12:37:17

标签: java json httprequest

我现在正试图在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 个答案:

答案 0 :(得分:3)

使用JSONTokener

只需2行代码
JSONTokener tokener = new JSONTokener(wikiRequest.openStream());
JSONObject root = new JSONObject(tokener);

答案 1 :(得分:2)

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

答案 2 :(得分:0)

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

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

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

答案 3 :(得分:0)

使用corn-httpclient&玉米转换器

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>