我在期待
System.out.println(java.net.URLEncoder.encode("Hello World", "UTF-8"));
输出:
你好%20世界
(20是ASCII十六进制空格码)
然而,我得到的是:
你好+世界
我用错方法了吗?我应该使用的正确方法是什么?
我在期待
System.out.println(java.net.URLEncoder.encode("Hello World", "UTF-8"));
输出:
你好%20世界
(20是ASCII十六进制空格码)
然而,我得到的是:
你好+世界
我用错方法了吗?我应该使用的正确方法是什么?
当前回答
查询参数
org.apache.commons.httpclient.util.URIUtil
URIUtil.encodeQuery(input);
如果你想转义URI中的字符
public static String escapeURIPathParam(String input) {
StringBuilder resultStr = new StringBuilder();
for (char ch : input.toCharArray()) {
if (isUnsafe(ch)) {
resultStr.append('%');
resultStr.append(toHex(ch / 16));
resultStr.append(toHex(ch % 16));
} else{
resultStr.append(ch);
}
}
return resultStr.toString();
}
private static char toHex(int ch) {
return (char) (ch < 10 ? '0' + ch : 'A' + ch - 10);
}
private static boolean isUnsafe(char ch) {
if (ch > 128 || ch < 0)
return true;
return " %$&+,/:;=?@<>#%".indexOf(ch) >= 0;
}
其他回答
这是预期的行为。URLEncoder实现了如何在HTML表单中编码url的HTML规范。
来自javadocs:
该类包含的静态方法 将String转换为 应用程序/ x-www-form-urlencoded MIME 格式。
和来自HTML规范:
应用程序/ x-www-form-urlencoded 使用此内容类型提交的表单 必须编码如下: 控件名称和值被转义。空格字符被替换 通过“+”
你必须更换它,例如:
System.out.println(java.net.URLEncoder.encode("Hello World", "UTF-8").replace("+", "%20"));
只是在Android上也在挣扎,设法偶然发现了Uri。encode(字符串,字符串)而特定于android (android.net.Uri)可能对一些有用。
静态字符串编码(字符串s,字符串允许)
以https://developer.android.com/reference/android/net/Uri.html编码(以)
该类执行application/x-www-form- urlenencoded -type编码,而不是百分比编码,因此替换为+是正确的行为。
从javadoc:
When encoding a String, the following rules apply: The alphanumeric characters "a" through "z", "A" through "Z" and "0" through "9" remain the same. The special characters ".", "-", "*", and "_" remain the same. The space character " " is converted into a plus sign "+". All other characters are unsafe and are first converted into one or more bytes using some encoding scheme. Then each byte is represented by the 3-character string "%xy", where xy is the two-digit hexadecimal representation of the byte. The recommended encoding scheme to use is UTF-8. However, for compatibility reasons, if an encoding is not specified, then the default encoding of the platform is used.
查询参数
org.apache.commons.httpclient.util.URIUtil
URIUtil.encodeQuery(input);
如果你想转义URI中的字符
public static String escapeURIPathParam(String input) {
StringBuilder resultStr = new StringBuilder();
for (char ch : input.toCharArray()) {
if (isUnsafe(ch)) {
resultStr.append('%');
resultStr.append(toHex(ch / 16));
resultStr.append(toHex(ch % 16));
} else{
resultStr.append(ch);
}
}
return resultStr.toString();
}
private static char toHex(int ch) {
return (char) (ch < 10 ? '0' + ch : 'A' + ch - 10);
}
private static boolean isUnsafe(char ch) {
if (ch > 128 || ch < 0)
return true;
return " %$&+,/:;=?@<>#%".indexOf(ch) >= 0;
}
这对我很有效
org.apache.catalina.util.URLEncoder ul = new org.apache.catalina.util.URLEncoder().encode("MY URL");