[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

How to read response from HttpClient

Posted on 2009-12-20
6
Medium Priority
?
1,885 Views
Last Modified: 2012-05-08
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

0
Comment
Question by:DJ_AM_Juicebox
6 Comments
 
LVL 86

Accepted Solution

by:
CEHJ earned 2000 total points
ID: 26091651
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
 

Author Comment

by:DJ_AM_Juicebox
ID: 26091660
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
 
LVL 27

Expert Comment

by:mrcoffee365
ID: 26091853
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
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
LVL 23

Expert Comment

by:cmalakar
ID: 26093078
Yes, that is how you should read the response in http-client 4.x.

getResponseBodyAsString( ) api is available in 3.x



0
 
LVL 23

Expert Comment

by:cmalakar
ID: 26093086
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
 
LVL 86

Expert Comment

by:CEHJ
ID: 26173620
:-)

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

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
Video by: Michael
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…
Suggested Courses
Course of the Month19 days, 13 hours left to enroll

873 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question