Boss wants us to send a HTTP GET with parameters in the body. I can't figure out how to do this using org.apache.commons.httpclient.methods.GetMethod or java.net.HttpURLConnection;.
GetMethod doesn't seem to take any parameters, and I'm not sure how to use HttpURLConnection for this.
Yes. In other words, any HTTP request message is allowed to contain a message body, and thus must parse messages with that in mind. Server semantics for GET, however, are restricted such that a body, if any, has no semantic meaning to the request.
GET requests don't have a request body, so all parameters must appear in the URL or in a header. While the HTTP standard doesn't define a limit for how long URLs or headers can be, mostHTTP clients and servers have a practical limit somewhere between 2 kB and 8 kB.
You can extends the HttpEntityEnclosingRequestBase class to override the inherited org.apache.http.client.methods.HttpRequestBase.getMethod() but by fact HTTP GET does not support body request and maybe you will experience trouble with some HTTP servers, use at your own risk :)
public class MyHttpGetWithEntity extends HttpEntityEnclosingRequestBase {
public final static String GET_METHOD = "GET";
public MyHttpGetWithEntity(final URI uri) {
super();
setURI(uri);
}
public MyHttpGetWithEntity(final String uri) {
super();
setURI(URI.create(uri));
}
@Override
public String getMethod() {
return GET_METHOD;
}
}
then
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
public class HttpEntityGet {
public static void main(String[] args) {
try {
HttpClient client = new DefaultHttpClient();
MyHttpGetWithEntity e = new MyHttpGetWithEntity("http://....");
e.setEntity(new StringEntity("mystringentity"));
HttpResponse response = client.execute(e);
System.out.println(IOUtils.toString(response.getEntity().getContent()));
} catch (Exception e) {
System.err.println(e);
}
}
}
HTTP GET method should NEVER have a body section. You can pass your parameters using URL query string or HTTP headers.
If you want to have a BODY section. Use POST or other methods.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With