commons httpclient - 将查询字符串参数添加到 GET/POST 请求

2024-03-21

我正在使用 commons HttpClient 对 Spring servlet 进行 http 调用。我需要在查询字符串中添加一些参数。所以我做了以下事情:

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);

但是,当我尝试使用读取 servlet 中的参数时

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

它返回 null。事实上parameterMap 是完全空的。当我在创建 HttpGet 请求之前手动将参数附加到 url 时,这些参数在 servlet 中可用。当我使用附加了 queryString 的 URL 从浏览器中点击 servlet 时,情况也是如此。

这里有什么错误?在 httpclient 3.x 中,GetMethod 有一个 setQueryString() 方法来附加查询字符串。 4.x 中的等价物是什么?


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

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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

commons httpclient - 将查询字符串参数添加到 GET/POST 请求 的相关文章

随机推荐