2013-03-29 3 views
1
HttpClient httpClient = new DefaultHttpClient(); 
HttpPost httpPost = new HttpPost(URL); 

try { 
    StringEntity documentStringified = new StringEntity(Obj.toString()); 
    httpPost.setEntity(documentStringified); 
} catch (UnsupportedEncodingException e) { 
    Log.d("UnsupportedEncodingException", e.toString()); 
} 

try { 
    HttpResponse response = httpClient.execute(httpPost); 
    Log.d("Response", response.toString()); 
} catch (IOException e) { 
    Log.d("IOException", e.toString()); 
} 

response을 얻을 수 없습니다. response.toString() 또는 response.getEntity.toString()의 응답을 인쇄하는 방법이 작동하지 않습니다.JSON 응답 받기 Android

콘텐츠 유형을 "application/json"으로 설정해야합니까?

답변

6

일반적인 방법은 다음과 같습니다

String result = EntityUtils.toString(response.getEntity()); 

또한, 당신이 응답 코드를 확인할 수 있습니다. 때때로 요청이 실패합니다.

int status = response.getStatusLine().getStatusCode(); 
if (status == 200) { 
    String result = EntityUtils.toString(response.getEntity());  
} 
+0

엔티티는 response.getEntity()입니다. 그렇습니까? – Kevin

+0

마지막 질문입니다. content-type : 'application/json'을 내 http – Kevin

+0

으로 설정하는 방법 예, 엔티티는 response.getEntity() –

1

응답이 없으므로 InputStream을 가져온 다음 Scanner을 사용하여 내용을 소비하십시오.

String responseContent = new Scanner(inputStream).useDelimiter("\\A").next(); 

useDelimiter("\\A") 그래서 next()는 모든 콘텐츠를 소비, "구분 기호가 스트림의 끝"을 의미한다.