我试图在其正文中发送一个带有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;
}
}
我们如何在这个例子中发送请求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);
}