如何从HttpResponse打印出返回的消息?

我的Android手机上有这个代码。

URI uri = new URI(url); HttpPost post = new HttpPost(uri); HttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(post); 

我有一个asp.net webform应用程序,在页面加载这个

  Response.Output.Write("It worked"); 

我想从HttpReponse中获取此响应并将其打印出来。 我该怎么做呢?

我尝试了response.getEntity().toString()但它似乎打印出内存中的地址。

谢谢

Solutions Collecting From Web of "如何从HttpResponse打印出返回的消息?"

使用ResponseHandler 。 一行代码。 有关使用它的示例Android项目,请参阅此处和此处 。

 public void postData() { // Create a new HttpClient and Post Header HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("http://www.yoursite.com/user"); try { // Add your data List nameValuePairs = new ArrayList(2); nameValuePairs.add(new BasicNameValuePair("id", "12345")); nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!")); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); // Execute HTTP Post Request ResponseHandler responseHandler=new BasicResponseHandler(); String responseBody = httpclient.execute(httppost, responseHandler); JSONObject response=new JSONObject(responseBody); } catch (ClientProtocolException e) { // TODO Auto-generated catch block } catch (IOException e) { // TODO Auto-generated catch block } } 

添加此post的组合并完成HttpClient – http://www.androidsnippets.org/snippets/36/

我会以旧的方式做到这一点。 如果您在响应中获得不同的内容types,它比ResponseHandler更具防弹性。

 ByteArrayOutputStream outstream = new ByteArrayOutputStream(); response.getEntity().writeTo(outstream); byte [] responseBody = outstream.toByteArray(); 

我使用了以下代码

 BufferedReader r = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); StringBuilder total = new StringBuilder(); String line = null; while ((line = r.readLine()) != null) { total.append(line); } r.close(); return total.toString(); 

此代码将返回整个响应消息作为String进行响应 ,并将状态代码作为intrsp中

 respond = response.getStatusLine().getReasonPhrase(); rsp = response.getStatusLine().getStatusCode();`