Java的URL编码:URLEncoder的主场迎战URI(Java URL encoding: U

2019-08-06 19:27发布

展望在W3学校URL编码的网页 ,它说, @应该被编码为%40 ,而space应该被编码为%20

我都试过URLEncoderURI ,但同样没有上面的正确:

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的错?)

Answer 1:

虽然我觉得从@fge答案是正确的,因为我使用的是第三方web服务上W3Schools的文章中概述的编码依赖,我也跟着从答案的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;
}


Answer 2:

URI语法被定义RFC 3986 (为一个查询字符串允许内容在3.4节中定义)。 Java的URI符合这个RFC,在其提到的几个注意事项的Javadoc 。

你会发现, pchar语法规则被定义为:

PChar类型=未保留/ PCT编码/子delims / “:”/ “@”

这意味着@是在查询字符串的法律

相信URI。 它做正确的,“合法”的东西。

最后,如果你有一个看的URLEncoder的Javadoc中 ,您可以看到它指出:

这个类包含一个字符串转换为应用程序/ x WWW的形式进行了urlencoded MIME格式的静态方法。

这是一样的东西由URI规范定义的查询字符串。



文章来源: Java URL encoding: URLEncoder vs. URI