获得JSON响应转换成字符串在Java中?(Getting JSON response into S

2019-09-23 12:40发布

我得到JSON格式的响应,当我做出API请求的API。

我得到这个当我做System.Out.Println的响应。

HTTP/1.1 200 OK [Date: Thu, 04 Oct 2012 20:33:18 GMT, Server: Apache/1.3.33 (Unix) PHP/4.4.0, Cache-control: no-cache, must-revalidate, no-cache="Set-Cookie", private, Expires: Fri, 01 Jan 1990 00:00:00 GMT, Pragma: no-cache, X-CreationTime: 0.051, Set-Cookie: DT=1349382798:29998:365-l4; path=/; expires=Fri, 01-Jan-2020 00:00:00 GMT; domain=.wunderground.com, Connection: close, Transfer-Encoding: chunked, Content-Type: application/json; charset=UTF-8]

但它不是预期的响应,响应应该是这样的,

response: {
name:
class:
}

我使用Apache的HTTP客户端。

DefaultHttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url); 
HttpResponse response = httpclient.execute(httpget);
System.out.println(response);

我应该怎么做未来,以获得预期的结果? 我只需要在正确的方向点。

Answer 1:

你需要做这样的事情,而不是:

HttpResponse response = httpclient.execute(httpget);
StringBuilder sb = new StringBuilder();
DataInputStream in = new DataInputStream(response.getEntity().getContent()); 
String line;     
while ((line = in.readLine()) != null) { 
    sb.append(line);
} 
in.close(); 
String json = sb.toString(); 


Answer 2:

我在这里回答我的问题:

Apache的网站更多的研究的一点点后,我发现这一点:

HttpEntity entity = response.getEntity();
System.out.println(EntityUtils.toString(entity));

相信我,这是很多更容易和工程就像一个魅力。



文章来源: Getting JSON response into String in Java?
标签: java json http