How to encode URL string in JavaIn this tutorial i will tell you How to encode URL string in Java. A URL String can be encoded using the URLEncoder class encode 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

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) {


Encoded URL %3C%21%5BCDATA%5B+%3CIMG+SRC%3D%22+%26%2314%3B+
Dncoded URL <![CDATA[ <IMG SRC=" &#14; javascript:document.vulnerable=true;"> ]]>

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

Reference : mkyoung

One thought on “How to encode URL string in Java

Leave a Reply

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