11.4. Sending Parameters in a Query String

Problem

You need to send query parameters in a URL.

Solution

Set the query string using the setQueryString( ) method on an instance of HttpMethod. Use URIUtil to encode any text included in a URL. The following example puts two parameters on the query string:

               import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.util.URIUtil;

HttpClient client = new HttpClient( );

String url = "http://www.discursive.com/cgi-bin/jccook/param_list.cgi";

HttpMethod method = new GetMethod( url );

// Set the Query String with setQueryString( )
method.setQueryString(URIUtil.encodeQuery("test1=O Reilly&blah=Whoop"));
System.out.println( "With Query String: " + method.getURI( ) );

client.executeMethod( method );

System.out.println( "Response:\n " + method.getResponseBodyAsString( ) );
method.releaseConnection( );

The param_list.cgi CGI script echoes all parameters received, and from the following output, you can see how URIUtil encodes the first parameter:

With Query String: http://www.discursive.com/cgi-bin/jccook/param_list.
cgi?test1=O%20Reilly&blah=Whoop
Response:
 These are the parameters I received:

test1:
  O Reilly
blah:
  Whoop

Tip

The question mark is understood, and you do not need to supply a leading question mark to the ...

Get Jakarta Commons Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.