2012-10-04 3 views
2

API 요청을 API에 보내면 JSON 형식의 응답이 표시됩니다.자바에서 JSON 응답을 String으로 가져오고 싶습니까?

내가 응답 System.Out.Println을 할 때 이것을 얻고 있습니다. 제가 아파치 HTTP 클라이언트를 사용하고

response: { 
name: 
class: 
} 

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] 

하지만 예상되는 응답하지 응답은 다음과 같이해야한다.

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

예상되는 결과를 얻으려면 어떻게해야합니까? 나는 단지 올바른 방향으로 한 점을 필요로한다.

답변

2

당신이 대신 같은 것을 수행해야합니다 :

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(); 
+0

[code] readLine [/ code]이 (가) 사용되지 않습니다. – user1601973

+0

그러면'BufferedReader'를 사용하십시오. –

+0

참고로 BufferedInputStream.getLine()에 의해 반환 된 일련의'String' 객체 대신'InputStream.read (CharBuffer)'로'CharBuffer'를 사용하는 것이 훨씬 더 효율적입니다. 메모리 할당과 줄 바꿈 검색을 모두 절약합니다. –

3

를 내가 여기에 내 자신의 질문에 대답하고있다 : 아파치 웹 사이트에서 더 많은 연구의 조금 후

을, 나는이 발견 :

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

나를 훨씬 더 쉽게 생각하고 매력처럼 작동합니다.

관련 문제