无法在GET请求中使用HTTPUrlConnection在标头中设置属性

时间:2014-08-25 12:56:52

标签: java rest header

我试图为此找到解决方案,甚至找到了许多解决方案,但没有解决我的问题。 我正在尝试实现一个消耗Restful web service的Java客户端。 我想在头文件中设置参数,我可以在我的Web服务器上检索。我的代码是;

URL url = new URL("http://servierIP/address");

HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);

conn.setRequestMethod("GET");
conn.setRequestProperty("firstParam", "hi");
conn.addRequestProperty("secondParam","12345" );

conn.setRequestProperty("Content-Type", "application/xml");
conn.connect();

然而,当我尝试从标题中获取值时,我得到NULL。 我尝试使用addRequestPropertysetRequestProperty两者进行此操作,但仍然没有在我的标题中设置值。

我尝试获取标头值时得到的输出是:

 null : [HTTP/1.1 200 OK]
 Expires : [Thu, 19 Nov 1981 08:52:00 GMT]
 Access-Control-Allow-Orgin : [*]
 Set-Cookie : [dsfjskfjdsfjskf  ---- some value]
 Access-Control-Allow-Methods : [*]
 Connection : [Keep-Alive]
 Server : [Apache/2.2.15 (CentOS)]
 X-Powered-By : [PHP/5.3.3]
 Cache-Control : [no-store, no-cache, must-revalidate, post-check=0, pre-check=0, public, public]
 Pragma : [no-cache, public, public]
 Date : [Tue, 26 Aug 2014 05:33:10 GMT]
 Transfer-Encoding : [chunked]
 Content-Type : [application/xml; charset=utf-8]

如果有人能解决这个问题,我将非常感激......

谢谢。

1 个答案:

答案 0 :(得分:0)

你试过Apache http client吗? 添加标题非常简单

DefaultHttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(urlString);
httpget.addHeader("my-custom-header", "value");
HttpResponse response = httpclient.execute(httpget);