Cheok Yan Cheng Cheok Yan Cheng - 1 year ago 112
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?

Answer Source

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"));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download