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#setEntit
Using torbinsky's answer I created the above class. This lets me use the same methods for HttpPost.
import java.net.URI;
import org.apache.http.client.methods.HttpPost;
public class HttpGetWithEntity extends HttpPost {
public final static String METHOD_NAME = "GET";
public HttpGetWithEntity(URI url) {
super(url);
}
public HttpGetWithEntity(String url) {
super(url);
}
@Override
public String getMethod() {
return METHOD_NAME;
}
}
How we can send request uri in this example just like HttpGet & HttpPost ???
public class HttpGetWithEntity extends HttpEntityEnclosingRequestBase
{
public final static String METHOD_NAME = "GET";
@Override
public String getMethod() {
return METHOD_NAME;
}
HttpGetWithEntity e = new HttpGetWithEntity();
e.setEntity(yourEntity);
response = httpclient.execute(e);
}
In addition torbinsky's answer, you can add these constructors to the class to make it easier to set the uri:
public HttpGetWithEntity(String uri) throws URISyntaxException{
this.setURI(new URI(uri));
}
public HttpGetWithEntity(URI uri){
this.setURI(uri);
}
The setURI
method is inherited from HttpEntityEnclosingRequestBase
and can also be used outside the constructor.
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);