lscesario
lscesario

Reputation: 21

Issue when getting response from Apache HttpClient

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

Upvotes: 0

Views: 3076

Answers (1)

lscesario
lscesario

Reputation: 21

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();
    }
}

Upvotes: 1

Related Questions