java uri,Java URL编码:URLEncoder与URI

Looking on the W3 Schools URL encoding webpage, it says that @ should be encoded as %40, and that space should be encoded as %20.

I've tried both URLEncoder and URI, but neither does the above properly:

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());

}

}

For some reason, URLEncoder does the email address correctly but not spaces, and URI does spaces currency but not email addresses.

How should I encode these 2 parameters to be consistent with what w3schools says is correct (or is w3schools wrong?)

解决方案

Although I think the answer from @fge is the right one, as I was using a 3rd party webservice that relied on the encoding outlined in the W3Schools article, I followed the answer from 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;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值