Cheok Yan Cheng Cheok Yan Cheng - 9 months ago 57
Java Question

URLEncoder not able to translate space character

I am expecting

System.out.println("Hello World", "UTF-8"));

to output:


(20 is ASCII Hex code for space)

However, what I get is:


Am I using the wrong method? What is the correct method I should be using?


This behaves as expected. The URLEncoder implements the HTML Specifications for how to encode URLs in HTML forms.

From the javadocs:

This class contains static methods for converting a String to the application/x-www-form-urlencoded MIME format.

and from the HTML Specification:


Forms submitted with this content type must be encoded as follows:

  1. Control names and values are escaped. Space characters are replaced by `+'

You will have to replace it, e.g.:

System.out.println("Hello World", "UTF-8").replace("+", "%20"));