我正在尝试在其正文中发送带有json对象的HTTP GET。有没有办法设置HttpClient HttpGet的主体?我正在寻找相当于HttpPost#setEntity。
答案 0 :(得分:29)
据我所知,你不能使用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);
答案 1 :(得分:5)
使用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;
}
}
答案 2 :(得分:0)
我们如何在这个例子中发送请求uri就像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);
}
答案 3 :(得分:0)
除了torbinsky的答案外,您还可以将这些构造函数添加到类中,以使设置uri更容易:
public HttpGetWithEntity(String uri) throws URISyntaxException{
this.setURI(new URI(uri));
}
public HttpGetWithEntity(URI uri){
this.setURI(uri);
}
setURI
方法是从HttpEntityEnclosingRequestBase
继承的,也可以在构造方法之外使用。