How to encode a URL string or form parameter in java

This is always advisable to encode URL or form parameters; plain form parameter is vulnerable to cross site attack, SQL injection and may direct our web application into some unpredicted output. A URL String or form parameters can be encoded using the URLEncoder class – static encode (String s, String enc) method.

For example, when a user enters following special characters, and your web application doesn’t handle encoding, it will caused cross site script attack.


<![CDATA[ <IMG SRC=" &#14; javascript:document.vulnerable=true;"> ]]>

Example to use URLEncoder to encode a string and URLDecoder to decode the encoded string


package com.mkyong;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

public class testEncode {

  public static void main(String args[]) {

    try {

	String url = "<![CDATA[ <IMG SRC=\" &#14; javascript:document.vulnerable=true;\"> ]]>";

	String encodedUrl = URLEncoder.encode(url, "UTF-8");

	System.out.println("Encoded URL " + encodedUrl);

	String decodedUrl = URLDecoder.decode(url, "UTF-8");

	System.out.println("Dncoded URL " + decodedUrl);

	} catch (UnsupportedEncodingException e) {

		System.err.println(e);

	}
    }
}

Result

Encoded URL %3C%21%5BCDATA%5B+%3CIMG+SRC%3D%22+%26%2314%3B+
javascript%3Adocument.vulnerable%3Dtrue%3B%22%3E+%5D%5D%3E
Dncoded URL  ]]>

Please remember always encode the URL string and form parameters to prevent all the vulnerability attacks.

Reference

  1. URLEncoder Javadoc

11 comments on “How to encode a URL string or form parameter in java

  1. The post is wrong by saying use URLEncoder for URL parameters. This class is supposed to be used for form parameter encoding and not for url encoding. Space in a url must be encoded as %20 and not as ‘+’. ‘+’ itself should be escaped in URL parameters, it is an unsafe char.

  2. should: String decodedUrl = URLDecoder.decode(url, “UTF-8”); , be: String decodedUrl = URLDecoder.decode(encodedUrl, “UTF-8”);

    proving the decoding of the encoded url, not the original url?

  3. Hello Mkyong, can you explain a little more about how encoding url or form parameters we can prevent some attacks like Sql Injection?

    Your post is very good, but i couldn’t undestand this part…

    If you prefer only post some links that explain this, would be very helpful too!

Leave a Comment

Your email address will not be published. Required fields are marked *