0

I'm trying to work with the response body of a HTTP POST action. I'm implementing the following method:

public class post2 {

    public final static void main(String[] args) throws Exception {

        CloseableHttpClient httpclient = HttpClients.createDefault();

        List<NameValuePair> formparams = new ArrayList <NameValuePair>();
        formparams.add(new BasicNameValuePair("login_id", myID));
        formparams.add(new BasicNameValuePair("api_key", myKey));
        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);
        HttpPost httppost = new HttpPost(myURL);
        httppost.setEntity(entity);

        CloseableHttpResponse response2 = httpclient.execute(httppost);

        try {

            System.out.println(response2.getStatusLine());
            HttpEntity entity2 = response2.getEntity();
            EntityUtils.consume(entity2);

            String responseBody = EntityUtils.toString(entity2);
            System.out.println("finalResult"+responseBody.toString());              
        }

        finally {
             httpclient.close();
        }
    }
}

I'm just receiving a "HTTP/1.1 200 OK", followed by:

Exception in thread "main" java.lang.ClassCastException: org.apache.http.impl.execchain.HttpResponseProxy cannot be cast to org.apache.http.HttpEntity
at post2.main(post2.java:62)

How should I recover the body information from the WebService?

Thanks, Leo

1
  • Got it... Had to move the EntityUtils.consume(entity2); to the bottom of the block... Commented May 19, 2015 at 18:31

1 Answer 1

1

Had to move EntityUtils.consume(entity2); to the end of the block:

public final static void main(String[] args) throws Exception {

    CloseableHttpClient httpclient = HttpClients.createDefault();

    List<NameValuePair> formparams = new ArrayList <NameValuePair>();
    formparams.add(new BasicNameValuePair("login_id", myID));
    formparams.add(new BasicNameValuePair("api_key", myKey));
    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);
    HttpPost httppost = new HttpPost(myURL);
    httppost.setEntity(entity);

    CloseableHttpResponse response2 = httpclient.execute(httppost);

    try{

        System.out.println(response2.getStatusLine());
        HttpEntity entity2 = response2.getEntity();
        String responseBody = EntityUtils.toString(entity2);
        System.out.println("finalResult"+responseBody.toString());
        EntityUtils.consume(entity2);


    }

    finally {

         httpclient.close();
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.