Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I send an HTTP GET with a body?

Tags:

java

servlets

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.

like image 865
MedicineMan Avatar asked Dec 12 '13 17:12

MedicineMan


People also ask

Can you send a GET request with a body?

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.

Can HTTP GET have body?

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.


2 Answers

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

  
        
like image 139
vzamanillo Avatar answered Sep 30 '22 14:09

vzamanillo


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.

like image 40
Loc Avatar answered Sep 30 '22 13:09

Loc