Java URL 编码 : URLEncoder vs. URI

标签 java url urlencode

查看 W3 Schools URL encoding webpage ,它说 @ 应该编码为 %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 错误?)一致

最佳答案

虽然我认为来自@fge 的答案是正确的,因为我使用的是依赖于 W3Schools 文章中概述的编码的第 3 方网络服务,但我遵循了来自 Java equivalent to JavaScript's encodeURIComponent that produces identical output? 的答案。

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 vs. URI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14321873/

相关文章:

java - 为 torrent 计算的 info_hash 不正确

javascript - 此 jsfiddle url 中的参数

java - sql 格式 'YYYY-MM-DD HH24:MI:SS.FF' 到 java 的日期格式问题

url - 当文件名包含 "?"和 "="字符时如何打开 URI?

java - 无法从 RecyclerView 中的 URL 加载图像

url - 在二维码中嵌入本地主机 URL

PHP:使随机字符串 URL 安全并撤消使其安全的任何内容

java - 为什么我不必导入我刚刚制作的类以在我的主类中使用它? ( java )

java - React-native 链接路径不正确

java - for循环中的动态变量?