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


Usually, parameters are accessed from a request in an already decoded format (via request.getParameter()), so no decoding is necessary. However, occasionally certain situations arise where you need to decode a string that has been URL encoded (for instance, by the URLEncoder.encode() method or the javascriptW escape() function).

The JavaSW URLDecoder.decode() method can perform this decoding for you. In the short code example below, we take a String, URL Encode it, URL Decode it, and display the results. We do the same thing with a second string. We specify that the encoding and decoding follows the "UTF-8" encoding scheme.

UrlEncoderAndDecoderTest.java

package test;

import java.net.URLDecoder;
import java.net.URLEncoder;

public class UrlEncoderAndDecoderTest {

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

		String param1BeforeEncoding = "hello there";
		String param1AfterEncoding = URLEncoder.encode(param1BeforeEncoding, "UTF-8");
		String param1AfterDecoding = URLDecoder.decode(param1AfterEncoding, "UTF-8");
		System.out.println("param1 before encoding:" + param1BeforeEncoding);
		System.out.println("param1 after encoding:" + param1AfterEncoding);
		System.out.println("param1 after decoding:" + param1AfterDecoding);

		String param2BeforeEncoding = "good-bye, friend";
		String param2AfterEncoding = URLEncoder.encode(param2BeforeEncoding, "UTF-8");
		String param2AfterDecoding = URLDecoder.decode(param2AfterEncoding, "UTF-8");
		System.out.println("param2 before encoding:" + param2BeforeEncoding);
		System.out.println("param2 after encoding:" + param2AfterEncoding);
		System.out.println("param2 after decoding:" + param2AfterDecoding);

	}

}

The console output from executing UrlEncoderAndDecoderTest is shown below. As you can see, the strings get URL-encoded so that spaces get replaced by plus signs and other characters get replaced by other special characters. Then, the strings are URL-decoded, which brings them back to their initial forms.

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

URL encoding is required much more often than URL decoding, since decoding usually takes place automatically during calls the request.getParameter(). However, it is good to know that URLDecoder.decode() exists for the occasional situation where it is needed.