如何打印出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并打印出来。 我该怎么做呢?

我尝试了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<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(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<String> 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 } } 

添加这个职位的组合,并完成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返回整个响应消息,在rsp中返回状态码,作为int

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