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

查看:48
本文介绍了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 将如下所示:

The resulting URI would look like:

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

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

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