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

我现在正试图在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); 

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

使用JSONTokener只需2行代码

 JSONTokener tokener = new JSONTokener(wikiRequest.openStream()); JSONObject root = new JSONObject(tokener); 

如果您正在使用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依赖:

  net.sf.corn corn-httpclient 1.0.0   net.sf.corn corn-converter 1.0.0