当前页面: 开发资料首页 → J2SE 专题 → URL传递参数中含有特殊符问题!100分相赠
摘要: URL传递参数中含有特殊符问题!100分相赠
* URL strings may not contain non-alphanumeric characters. All
* non-alphanumeric characters are converted to the escape sequence "%XX",
* where XX is the hexadecimal value of that character's code.
*
* Note that the space character " " is NOT converted to "+". That is a
* common misconception. "+" represents a space only in query strings, not
* in the URL. "%20" is how an actual space character must be passed in an
* URL, and is also an acceptable way of passing a space in a query string.
*
* @param string
* The string to convert.
*
* @return The URL-encoded version of the given string.
*/
public static String urlEncode(String src) {
StringBuffer result = new StringBuffer();
int length = (src == null) ? 0 : src.length();
for (int i = 0; i < length; i++) {
int ch = src.charAt(i) & 0xff;
if (safeUrl[ch]) {
result.append((char) ch);
} else {
result.append('%');
result.append(Character.forDigit((ch >> 4) & 0x0f, 16));
result.append(Character.forDigit(ch & 0x0f, 16));
}
}
return result.toString();
}
/**
* Decodes a URL-encoded string by replacing all the "%XX" escape sequences
* in the string with the corresponding character.
*
* Malformed "%XX" sequences are silently ignored.
*
* @param string
* The URL-encoded string.
*
* @return The decoded version of the given string.
*/
public static String urlDecode(String src) {
if (src == null) {
return "";
}
int i = src.indexOf('%');
if (i < 0) {
return src;
}
StringBuffer result = new StringBuffer(src.substring(0, i));
int length = src.length();
for (; i < length; i++) {
char ch = src.charAt(i);
if (ch == '%') {
try {
ch = (char) Integer.parseInt(src.substring(i + 1, i + 3),
16);
i += 2;
} catch (Exception e) {
// Ignore malformed % sequences, just insert the '%'.
}
}
result.append(ch);
}
return result.toString();
}
}