How do I add query parameters to a GetMethod (using Java commons-httpclient)?

Ross picture Ross · Oct 20, 2008 · Viewed 71.4k times · Source

Using Apache's commons-httpclient for Java, what's the best way to add query parameters to a GetMethod instance? If I'm using PostMethod, it's very straightforward:

PostMethod method = new PostMethod();
method.addParameter("key", "value");

GetMethod doesn't have an "addParameter" method, though. I've discovered that this works:

GetMethod method = new GetMethod("http://www.example.com/page");
method.setQueryString(new NameValuePair[] {
    new NameValuePair("key", "value")
});

However, most of the examples I've seen either hard-code the parameters directly into the URL, e.g.:

GetMethod method = new GetMethod("http://www.example.com/page?key=value");

or hard-code the query string, e.g.:

GetMethod method = new GetMethod("http://www.example.com/page");
method.setQueryString("?key=value");

Is one of these patterns to be preferred? And why the API discrepancy between PostMethod and GetMethod? And what are all those other HttpMethodParams methods intended to be used for?

Answer

Ryan Guest picture Ryan Guest · Oct 20, 2008

Post methods have post parameters, but get methods do not.

Query parameters are embedded in the URL. The current version of HttpClient accepts a string in the constructor. If you wanted to add the key, value pair above, you could use:

String url = "http://www.example.com/page?key=value";
GetMethod method = new GetMethod(url);

A good starting tutorial can be found on the Apache Jakarta Commons page.

Update: As suggested in the comment, NameValuePair works.

GetMethod method = new GetMethod("example.com/page"); 
method.setQueryString(new NameValuePair[] { 
    new NameValuePair("key", "value") 
});