首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Java URL编码: URLEncoder与URI

Java URL编码: URLEncoder与URI
EN

Stack Overflow用户
提问于 2013-01-14 23:54:26
回答 1查看 80.1K关注 0票数 23

查看W3 Schools URL encoding webpage,它表明@应该编码为%40space应该编码为%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是错误的?)

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-01-20 20:59:10

尽管我认为@fge的答案是正确的,因为我使用的是依赖于W3Schools文章中概述的编码的第三方was服务,但我遵循了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;
}
票数 43
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14321873

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档