How to read response from HttpClient

Hi,

I have the following code which makes a POST - is the way I'm reading the response correctly? I just want to get the text output the server is sending back. This is the snippet of interest:

  StringBuilder sbResponse = new StringBuilder(256);
  DataInputStream inStream = new DataInputStream(response.getEntity().getContent());
  String line;    
  while ((line = inStream.readLine()) != null) {
      sbResponse.append(line);
   }
   inStream.close();  
   String response = sbResponse.toString();

the full code is attached below. Any other considerations I need to make with this?

Thanks

public void postData() 
{
    // Create a new HttpClient and Post Header
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");

    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
        HttpResponse response = httpclient.execute(httppost);

        StringBuilder sbResponse = new StringBuilder(256);
        DataInputStream inStream = new DataInputStream(response.getEntity().getContent()); 
        String line;     
        while ((line = inStream.readLine()) != null) { 
            sbResponse.append(line);
        } 
        inStream.close(); 

        // All done.
        String response = sbResponse.toString(); 
        
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
    } catch (IOException e) {
        // TODO Auto-generated catch block
    }
}

Open in new window

DJ_AM_JuiceboxAsked:
Who is Participating?
 
CEHJConnect With a Mentor Commented:
Unfortunately that's not optimal. See the following for an example (ignore the gui stuff). You should be calling getResponseBodyAsString

http://svn.apache.org/viewvc/httpcomponents/oac.hc3x/trunk/src/examples/ClientApp.java?view=markup
0
 
DJ_AM_JuiceboxAuthor Commented:
Hi CEHJ,

What do I call getResponseBodyAsString() on though - the HttpResponse and HttpPost objects don't seem to expose that method?

Is the above wrong, will it not work? Or will it work, just that it could be faster?

Thanks
0
 
mrcoffee365Commented:
Have you tried your code?  Do you get your response back from the server?

I don't see much improvement in the link provided by CEHJ above, but there are many things about http interaction that you are not doing, such as handling cookies and error conditions.  Otherwise, your basic flow seems right -- make a connection, get the response and read it.  Reading the response line by line should be fine.

But trying to run the code is the best way to tell if it's not doing what you want.  Then, if you can't figure out how to get what you want, you can post the problem here.
0
Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
cmalakarCommented:
Yes, that is how you should read the response in http-client 4.x.

getResponseBodyAsString( ) api is available in 3.x



0
 
cmalakarCommented:
getContent( ) will only give the response body.

If you want to read any other headers in the http response you get.. you have to use..  other api's avaible in HttpEntity

 [ response.getEnttity( ) will give the instance of HttpEntity]
0
 
CEHJCommented:
:-)

That is the optimal way if you need a String. Otherwise, you can look at things like


http://hc.apache.org/httpclient-3.x/apidocs/org/apache/commons/httpclient/HttpMethod.html#getResponseBodyAsStream()
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.