Joh*_*lly 20 java url urlencode
查看W3 Schools URL编码网页,它表示@应该编码为%40,并且space应编码为%20.
我都试过URLEncoder和URI,但同样没有上面的正确:
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)
fge*_*fge 16
URI语法由RFC 3986定义(查询字符串的允许内容在3.4节中定义).Java URI符合此RFC,其Javadoc中提到了一些警告.
您会注意到pchar语法规则定义如下:
pchar = unreserved/pct-encoded/sub-delims /":"/"@"
这意味着a 在查询字符串中@是合法的.
信任URI.它会做正确的"合法"的事情.
最后,如果您查看URLEncoder的Javadoc,您会看到它指出:
此类包含用于将String转换为application/x-www-form-urlencoded MIME格式的静态方法.
这是不是一回事由URI规范定义的查询字符串.
| 归档时间: |
|
| 查看次数: |
70159 次 |
| 最近记录: |