'How do I send an HTTP GET with a body?

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.



Solution 1:[1]

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

  
        

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 DarkMakukudo