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 方 Web 服务,所以我遵循了 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/57159214/

相关文章:

java - 从功能上遍历图像的惯用方式

ios - 打开时处理错误URL的正确方法

javascript - URLEncode - 让它按照我想要的方式工作

javascript - encodeURIComponent() 似乎没有使用 dojo.xhrPost() 编码 '+' 字符

java - 在 Android 上的评论屏幕上实现网络调用的最佳实践是怎样的?

java - 使用用户输入的对象数量创建对象

java - Java 中 MySQL Callable 语句为 null

java - 使用 Java 获取 Internet 文件并将其创建为 File 对象?

java - HTTPS 请求和多线程

java - 西类牙语字符和 URISyntaxException