Differences between URLEncoder and HTML Form URL Encoding
In attempting to encode a string containing a space character using java.net.URLEncoder, you may notice an unexpected result. The output does not follow the expected "Hello World" format but instead yields "Hello World." This stems from the nuance between URLEncoder's behavior and HTML form URL encoding.
The URLEncoder operates according to HTML specification for encoding URLs in HTML forms. As per the HTML specification, control names and values must escape space characters, not with " ," but with the " " symbol.
However, your requirement may be encoding a space character specifically as " ." To achieve this, a simple replacement operation can be performed on the encoded string:
String encodedString = java.net.URLEncoder.encode("Hello World", "UTF-8"); String correctedString = encodedString.replace("+", "%20");
This correction replaces the " " symbol with " ," resulting in the desired "Hello World" format.
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!