Apache HttpClient GET with body
2022-09-01 14:03:49
我正在尝试发送一个带有json对象的HTTP GET。有没有办法设置HttpClient HttpGet的主体?我正在寻找HttpPost#setEntity的等效物。
我正在尝试发送一个带有json对象的HTTP GET。有没有办法设置HttpClient HttpGet的主体?我正在寻找HttpPost#setEntity的等效物。
据我所知,你不能使用Apache库附带的默认HttpGet类来做到这一点。但是,您可以对 HttpEntityEnclosingRequestBase 实体进行子类化,并将该方法设置为 GET。我还没有测试过这个,但我认为以下示例可能是您要查找的:
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;
}
}
编辑:
然后,您可以执行以下操作:
...
HttpGetWithEntity e = new HttpGetWithEntity();
...
e.setEntity(yourEntity);
...
response = httpclient.execute(e);
使用Torbinsky的答案,我创建了上面的类。这让我对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;
}
}