How do I encode URL parameters?
Author: Deron Eriksson
Description: This Java tutorial describes how to encode URL parameters using the URLEncoder.encode() method.
Tutorial created using: Windows XP || JDK 1.5.0_09 || Eclipse Web Tools Platform 1.5.4 || Tomcat 5.5.20


When using the GET method, parameter names and their values get submitted on the URL string after a question mark. Different parameter name/value pairs are separated by ampersands. Below is an example of submitting two parameters to the 'my-demo-servlet' servletW. The first parameter is called 'param1' and has a value of 'hello', and the second parameter is called 'param2' and has a value of 'goodbye'.

http://localhost:8080/demo/my-demo-servlet?param1=hello&param2=goodbye

However, what happens if the parameter value in the URL string has a space or some other special character? Submitting an HTMLW form will result in special characters being automatically converted to special codes for us. However, sometimes it is necessary to encode these characters without the aid of an HTML form. JavaSW has a class called URLEncoder that can encode these characters so that they are properly handled. The encode method takes two parameters, the string to be encoded and the encoding scheme. Unless you're smoking crack, you probably want the encoding scheme to be "UTF-8".

Let's say param1's value is "hello there" and param2's value is "good-bye, friend". Let's convert these strings using the URLEncoder.encode() method so that we can properly add them as parameters to the URL above. We'll use "UTF-8" as the encoding scheme.

UrlEncoderTest.java

package test;

import java.net.URLEncoder;

public class UrlEncoderTest {

	public static void main(String[] args) throws Exception {

		String param1Before = "hello there";
		String param1After = URLEncoder.encode(param1Before, "UTF-8");
		System.out.println("param1 before:" + param1Before);
		System.out.println("param1 after:" + param1After);

		String param2Before = "good-bye, friend";
		String param2After = URLEncoder.encode(param2Before, "UTF-8");
		System.out.println("param2 before:" + param2Before);
		System.out.println("param2 after:" + param2After);

	}

}

If we execute the code above, we obtain

param1 before:hello there
param1 after:hello+there
param2 before:good-bye, friend
param2 after:good-bye%2C+friend

Notice that the spaces have been converted to plus signs, and the comma has been converted to %2C, which is the encoded representation of this special character. If we update our URL above to feature these new parameter values, we would see the following:

http://localhost:8080/demo/my-demo-servlet?param1=hello+there&param2=good-bye%2C+friend

The URLEncoder class will probably become your friend if you write Java web applications. It's easy to use, since you just need to call its 'encode' method and get back the returned String value. Stick with "UTF-8" encoding unless you're writing something really funky.