Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apache HttpClient GET with body

I am trying to send an HTTP GET with a json object in its body. Is there a way to set the body of an HttpClient HttpGet? I am looking for the equivalent of HttpPost#setEntity.

like image 629
Scott Swank Avatar asked Sep 21 '12 17:09

Scott Swank


People also ask

How do I get HTTP body response?

To get the response body as a string we can use the EntityUtils. toString() method. This method read the content of an HttpEntity object content and return it as a string. The content will be converted using the character set from the entity object.

What is HttpClients createDefault ()?

createDefault() Creates CloseableHttpClient instance with default configuration. static CloseableHttpClient. createMinimal() Creates CloseableHttpClient instance that implements the most basic HTTP protocol support.


1 Answers

From what I know, you can't do this with the default HttpGet class that comes with the Apache library. However, you can subclass the HttpEntityEnclosingRequestBase entity and set the method to GET. I haven't tested this, but I think the following example might be what you're looking for:

import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;  public class HttpGetWithEntity extends HttpEntityEnclosingRequestBase {     public final static String METHOD_NAME = "GET";      @Override     public String getMethod() {         return METHOD_NAME;     } } 

Edit:

You could then do the following:

... HttpGetWithEntity e = new HttpGetWithEntity(); ... e.setEntity(yourEntity); ... response = httpclient.execute(e); 
like image 182
torbinsky Avatar answered Sep 29 '22 21:09

torbinsky