Java URL编码:URLEncoder与URI

Joh*_*lly 20 java url urlencode

查看W3 Schools 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());
    }
}
Run Code Online (Sandbox Code Playgroud)

出于某种原因,URLEncoder电子邮件地址是否正确但不是空格,并且URI空格而不是电子邮件地址.

我应该如何编码这两个参数以符合w3schools所说的正确(或w3schools错误?)

Joh*_*lly 36

虽然我认为@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;
}
Run Code Online (Sandbox Code Playgroud)

  • 您忘记了对解码URL很重要的&符号(对于GET或POST方法),因为它是用于分隔请求中的键的符号 (2认同)

fge*_*fge 16

URI语法由RFC 3986定义(查询字符串的允许内容在3.4节中定义).Java URI符合此RFC,其Javadoc中提到了一些警告.

您会注意到pchar语法规则定义如下:

pchar = unreserved/pct-encoded/sub-delims /":"/"@"

这意味着a 在查询字符串中@合法的.

信任URI.它做正确的"合法"的事情.

最后,如果您查看URLEncoderJavadoc,您会看到它指出:

此类包含用于将String转换为application/x-www-form-urlencoded MIME格式的静态方法.

这是不是一回事由URI规范定义的查询字符串.

  • 这很奇怪...... URI的Javadocs声明它遵循RFC 2396,即使在[Java 8](http://docs.oracle.com/javase/8/docs/api/java/net/URI.html)中也是如此,其中[RFC 2396](https://tools.ietf.org/html/rfc2396)来自1998年,它已经被[RFC 3986]废弃了**(https://tools.ietf.org/html/rfc3986)自2005年以来 (4认同)