Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print out returned message from HttpResponse?

I have this code on my Android phone.

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

I have a asp.net webform application that has in the page load this

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

I want to grab this Response from the HttpReponse and print it out. How do I do this?

I tried response.getEntity().toString() but it just seems to print out the address in memory.

Thanks

like image 618
chobo2 Avatar asked Apr 03 '10 23:04

chobo2


People also ask

How do I get response body from Org Apache Httpresponse?

To get the response body as a string we can use the EntityUtils. toString() method. This method read the content of an HttpEntity object content and return it as a string. The content will be converted using the character set from the entity object.


2 Answers

Use ResponseHandler. One line of code. See here and here for sample Android projects using it.

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     } }  

add combination of this post and complete HttpClient at - http://www.androidsnippets.org/snippets/36/

like image 91
CommonsWare Avatar answered Oct 06 '22 03:10

CommonsWare


I would just do it the old way. It's a more bulletproof than ResponseHandler, in case you get different content types in the response.

ByteArrayOutputStream outstream = new ByteArrayOutputStream(); response.getEntity().writeTo(outstream); byte [] responseBody = outstream.toByteArray(); 
like image 45
hnviet Avatar answered Oct 06 '22 02:10

hnviet