Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 728
Oceanic Avatar asked Mar 28 '12 12:03

Oceanic


People also ask

CAN POST request accept query parameters?

POST should not have query param. You can implement the service to honor the query param, but this is against REST spec.

Can a post request have a query string?

A POST request can include a query string, however normally it doesn't - a standard HTML form with a POST action will not normally include a query string for example.

CAN GET method have query parameters?

When the GET request method is used, if a client uses the HTTP protocol on a web server to request a certain resource, the client sends the server certain GET parameters through the requested URL. These parameters are pairs of names and their corresponding values, so-called name-value pairs.


1 Answers

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 
like image 57
Sublimemm Avatar answered Oct 05 '22 03:10

Sublimemm