Apache HttpClient GET with body

假如想象 提交于 2019-11-27 22:07:47
torbinsky

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!