I am trying to send an HTTP GET with a json object in its body. Is there a way to set the body of an HttpClient HttpGet? I am looking for the equivalent of HttpPost#setEntity.
问问题
23594 次
4 回答
40
据我所知,您不能使用 Apache 库附带的默认 HttpGet 类来执行此操作。但是,您可以子类化HttpEntityEnclosureRequestBase实体并将方法设置为 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);
于 2012-09-21T18:03:42.497 回答
7
使用托宾斯基的回答我创建了上面的类。这让我可以对 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;
}
}
于 2014-07-29T15:44:10.460 回答
1
在这个例子中,我们如何像 HttpGet 和 HttpPost 一样发送请求 uri ???
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);
}
于 2017-12-22T14:29:39.213 回答
0
除了 torbinsky 的回答,您可以将这些构造函数添加到类中,以便更轻松地设置 uri:
public HttpGetWithEntity(String uri) throws URISyntaxException{
this.setURI(new URI(uri));
}
public HttpGetWithEntity(URI uri){
this.setURI(uri);
}
该setURI
方法继承自HttpEntityEnclosingRequestBase
构造函数,也可以在构造函数之外使用。
于 2019-07-31T18:23:25.477 回答