查看 W3 Schools URL编码网页,它说@
应该被编码为%40
,而space
应该被编码为%20
。
我尝试过URLEncoder
和URI
,但是都不能正确地执行上述操作:
import java.net.URI;
import java.net.URLEncoder;
public class Test {
public static void main(String[] args) throws Exception {
// Prints me%40home.com (CORRECT)
System.out.println(URLEncoder.encode("me@home.com", "UTF-8"));
// Prints Email+Address (WRONG: Should be Email%20Address)
System.out.println(URLEncoder.encode("Email Address", "UTF-8"));
// http://www.home.com/test?Email%20Address=me@home.com
// (WRONG: it has not encoded the @ in the email address)
URI uri = new URI("http", "www.home.com", "/test", "Email Address=me@home.com", null);
System.out.println(uri.toString());
}
}
由于某些原因,URLEncoder
可以正确处理电子邮件地址但无法处理空格,而 URI
可以处理空格但无法处理电子邮件地址。
我应该如何对这两个参数进行编码,以与 W3Schools 给出的正确编码一致(或者是 W3Schools 错了?)
URLEncoder
不按照 URL 规范进行编码,而是按照application/x-www-form-urlencoded
MIME 格式进行编码(这是大多数应用服务器期望的参数键/值格式)。URI
类型根据其文档进行编码 - 也就是说,它不是一个完整的 URL 构建器。请注意,URI 的不同部分有不同的规则。有关更多分析,请参见此帖子。 - McDowell