Java URL编码:URLEncoder与URI [英] Java URL encoding: URLEncoder vs. URI
问题描述
查看 W3学校网址编码网页,它说 @
应编码为%40
,而空格
应编码为%20
。
Looking on the W3 Schools URL encoding webpage, it says that @
should be encoded as %40
, and that space
should be encoded as %20
.
我已尝试过两次 URLEncoder
和 URI
,但上述情况都不正确:
I've tried both URLEncoder
and URI
, but neither does the above properly:
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
确实是空格而不是电子邮件地址。
For some reason, URLEncoder
does the email address correctly but not spaces, and URI
does spaces currency but not email addresses.
我应该如何对这2个参数进行编码以与w3schools所说的正确(或w3schools错误?)一致?
How should I encode these 2 parameters to be consistent with what w3schools says is correct (or is w3schools wrong?)
推荐答案
<虽然我认为@fge的答案是正确的,因为我使用的是依赖于W3Schools文章中概述的编码的第三方Web服务,但我遵循了 Java相当于生成相同输出的JavaScript的encodeURIComponent?
public static String encodeURIComponent(String s) {
String result;
try {
result = URLEncoder.encode(s, "UTF-8")
.replaceAll("\\+", "%20")
.replaceAll("\\%21", "!")
.replaceAll("\\%27", "'")
.replaceAll("\\%28", "(")
.replaceAll("\\%29", ")")
.replaceAll("\\%7E", "~");
} catch (UnsupportedEncodingException e) {
result = s;
}
return result;
}
这篇关于Java URL编码:URLEncoder与URI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!