2012-09-21 65 views
14

我想发送一个HTTP GET与它的正文中的json对象。有没有办法设置HttpClient HttpGet的主体?我正在寻找相当于HttpPost#setEntity。Apache HttpClient GET与正文

+0

几乎重复:http://stackoverflow.com/questions/978061/http-get-with-request-body –

+0

尼基塔 - 我的问题是相似的,你发布一个,但是我具体怎么问通过Apache HttpClient API来完成。谢谢你。 –

+0

答案是不可能的。根据规范,GET请求不能包含主体。您需要使用POST请求。 –

回答

20

从我所知道的,你不能用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); 
+0

不错。谢谢。 –

+0

不客气。让我们知道它是否可行? :) – torbinsky

+0

这种方法有效吗? – Jilberta

4

使用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; 
    } 
} 
+0

我尝试了上面的代码与Web服务,我需要谈谈我的项目,并没有去。我刚收到服务守护进程日志“内部应用程序错误,关闭连接。”。 Jersey为实体提供了一个HttpGet(用不同的方式),但是可惜的是Apache不支持。这个特定的Web服务真正需要一个GET请求,而不是一个POST。 –

0

我们如何能在这个例子就像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); 
}