有时候我们会有一些奇怪的需求,比如使用带body的GET请求来请求数据,虽然HTTP协议里并没有禁止使用带body的GET请求,但是一般我们并不使用这种请求格式,而且HttpClient本身并没有定义带body的GET请求。此时怎么办呢?
我们可以自己定义一个带body的GET请求。首先,我们可以定义一个继承了 HttpEntityEnclosingRequestBase 的 HttpGetWithEntity 类,设置其请求方法为 GET:
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import java.net.URI;
public class HttpGetWithEntity extends HttpEntityEnclosingRequestBase {
private final static String METHOD_NAME = "GET";
@Override
public String getMethod() {
return METHOD_NAME;
}
public HttpGetWithEntity() {
super();
}
public HttpGetWithEntity(final URI uri) {
super();
setURI(uri);
}
HttpGetWithEntity(final String uri) {
super();
setURI(URI.create(uri));
}
}
然后,在调用时
HttpGetWithEntity oHttpGet = new HttpGetWithEntity(url);
HttpEntity httpEntity = new StringEntity(body, ContentType.APPLICATION_JSON);
oHttpGet.setEntity(httpEntity);
参考
https://stackoverflow.com/questions/12535016/apache-httpclient-get-with-body