troubleshooting Question

How to read response from HttpClient

Avatar of DJ_AM_Juicebox
DJ_AM_Juicebox asked on
Java
6 Comments1 Solution1940 ViewsLast Modified:
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
    }
}
Join the community to see this answer!
Join our exclusive community to see this answer & millions of others.
Unlock 1 Answer and 6 Comments.
Join the Community
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 6 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros