When attempting to encode a string using URLEncoder, you might encounter an unexpected behavior where spaces are converted to ' ' symbols instead of the expected ' ' hexadecimal code.
The URLEncoder class adheres to the HTML Specifications for encoding URLs in HTML forms. According to these specifications, spaces should be replaced with ' ' symbols for parameters in application/x-www-form-urlencoded MIME format.
To achieve the desired encoding where spaces are converted to ' ', you can perform the following steps:
String encodedString = java.net.URLEncoder.encode("Hello World", "UTF-8"); encodedString = encodedString.replace("+", "%20");
This will replace all ' ' symbols with ' ', resulting in the correct encoding according to your expectations.
The above is the detailed content of Why Does URLEncoder Encode Spaces as ' ' Instead of ' '?. For more information, please follow other related articles on the PHP Chinese website!