Home  >  Article  >  Java  >  Why Does `URLEncoder` Encode Spaces as ' ' Instead of ' '?

Why Does `URLEncoder` Encode Spaces as ' ' Instead of ' '?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-11 16:35:031036browse

Why Does `URLEncoder` Encode Spaces as

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn