commons httpclient - Adding query string parameters to GET/POST request

Oceanic picture Oceanic · Mar 28, 2012 · Viewed 153.3k times · Source

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

However when i try to read the parameter in the servlet using

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

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.

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?

Answer

Sublimemm picture Sublimemm · Feb 4, 2013

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

The resulting URI would look like:

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