commons httpclient-将查询字符串参数添加到GET/POST请求 [英] commons httpclient - Adding query string parameters to GET/POST request

查看:166
本文介绍了commons httpclient-将查询字符串参数添加到GET/POST请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Commons HttpClient对Spring servlet进行http调用.我需要在查询字符串中添加一些参数.因此,我执行以下操作:

I am using commons HttpClient to make an http call to a Spring servlet. I need to add a few parameters in the query string. So I do the following:

HttpRequestBase request = new HttpGet(url);
HttpParams params = new BasicHttpParams();
params.setParameter("key1", "value1");
params.setParameter("key2", "value2");
params.setParameter("key3", "value3");
request.setParams(params);
HttpClient httpClient = new DefaultHttpClient();
httpClient.execute(request);

但是,当我尝试使用

((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest().getParameter("key");

它返回空值.实际上parameterMap完全是空的.当我在创建HttpGet请求之前将参数手动添加到url时,该参数在servlet中可用.当我使用附加了queryString的URL从浏览器中访问servlet时,情况相同.

it returns null. In fact the parameterMap is completely empty. When I manually append the parameters to the url before creating the HttpGet request, the parameters are available in the servlet. Same when I hit the servlet from the browser using the URL with queryString appended.

这是什么错误?在httpclient 3.x中,GetMethod具有setQueryString()方法来附加查询字符串. 4.x中的等效项是什么?

What's the error here? In httpclient 3.x, GetMethod had a setQueryString() method to append the querystring. What's the equivalent in 4.x?

推荐答案

以下是使用HttpClient 4.2及更高版本添加查询字符串参数的方法:

Here is how you would add query string parameters using HttpClient 4.2 and later:

URIBuilder builder = new URIBuilder("http://example.com/");
builder.setParameter("parts", "all").setParameter("action", "finish");

HttpPost post = new HttpPost(builder.build());

结果URI看起来像:

http://example.com/?parts=all&action=finish

这篇关于commons httpclient-将查询字符串参数添加到GET/POST请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆