2013-03-29 127 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()消耗所有的内容。