java版本的escape和unescape函數(shù)

字號(hào):

有時(shí)候我們?cè)谔幚眄撁嫣峤贿^來的中文產(chǎn)生亂碼不容易解決時(shí),比如頁面選擇了別的編碼,Examda提示: 而 AJAX 是用的 UTF-8 字符集,我們可以對(duì)要發(fā)送到服務(wù)器的中文用 Javascript 的 escape 函數(shù)進(jìn)行編碼,然而 Java 中又沒有相應(yīng)的 unescape 函數(shù)。
    而且 Java 中的 java.net.URLDecoder/java.net.URLEncoder 也對(duì)應(yīng)不上 javascript 的 encodeURI/decodeURI 和 encodeURIComponent/decodeURIComponent 函數(shù)。
    Javascript 的 escape/unescape 函數(shù)的代碼。
    public class EscapeUnescape {
    public static String escape(String src) {
    int i;
    char j;
    StringBuffer tmp = new StringBuffer();
    tmp.ensureCapacity(src.length() * 6);
    for (i = 0; i < src.length(); i++) {
    j = src.charAt(i);
    if (Character.isDigit(j) || Character.isLowerCase(j)
    || Character.isUpperCase(j))
    tmp.append(j);
    else if (j < 256) {
    tmp.append("%");
    if (j < 16)
    tmp.append("0");
    tmp.append(Integer.toString(j, 16));
    } else {
    tmp.append("%u");
    tmp.append(Integer.toString(j, 16));
    }
    }
    return tmp.toString();
    }
    public static String unescape(String src) {
    StringBuffer tmp = new StringBuffer();
    tmp.ensureCapacity(src.length());
    int lastPos = 0, pos = 0;
    char ch;
    while (lastPos < src.length()) {
    pos = src.indexOf("%", lastPos);
    if (pos == lastPos) {
    if (src.charAt(pos + 1) == 'u') {
    ch = (char) Integer.parseInt(src
    .substring(pos + 2, pos + 6), 16);
    tmp.append(ch);
    lastPos = pos + 6;
    } else {
    ch = (char) Integer.parseInt(src
    .substring(pos + 1, pos + 3), 16);
    tmp.append(ch);
    lastPos = pos + 3;
    }
    } else {
    if (pos == -1) {
    tmp.append(src.substring(lastPos));
    lastPos = src.length();
    } else {
    tmp.append(src.substring(lastPos, pos));
    lastPos = pos;
    }
    }
    }
    return tmp.toString();
    }
    public static void main(String[] args) {
    String tmp = "中文";
    System.out.println("testing escape : " + tmp);
    tmp = escape(tmp);
    System.out.println(tmp);
    System.out.println("testing unescape :" + tmp);
    System.out.println(unescape("%u6211%u4eec"));
    }
    }
    對(duì)于傳送后偶爾會(huì)出現(xiàn)亂碼的中文字符串用 javascript 的 escape 編碼后,傳到服務(wù)器,就能用上面的方法 unescape 解碼了,escape 與 encodeURI 可是不一樣的