2013-03-29 128 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。如何在Logger or console.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

and entity is nothing but response.getEntity()right? – Kevin

+0

最後一個問題,我如何設置內容類型:'application/json'到我的http – Kevin

+0

是的,實體是response.getEntity() –

1

從響應中獲取InputStream,然後使用Scanner消耗其內容。

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

useDelimiter("\\A")意思是「分隔符是流的末尾」,所以next()消耗所有的內容。