Java解決Illegal hex characters in escape

解決Illegal hex characters in escape (%) pattern - For input string


public class EscapeUnescape {

    /**
     * escape 編碼
     * @param src
     * @return
     */
    public static String escape(String src) {
        int i;
        char j;
        StringBuffer buffer = new StringBuffer();
        buffer.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))
                buffer.append(j);
            else if (j < 256) {
                buffer.append("%");
                if (j < 16)
                    buffer.append("0");
                buffer.append(Integer.toString(j, 16));
            } else {
                buffer.append("%u");
                buffer.append(Integer.toString(j, 16));
            }
        }
        return buffer.toString();
    }

    /**
     * unescape 解碼
     * @param src
     * @return
     */
    public static String unescape(String src) {
        StringBuffer buffer = new StringBuffer();
        buffer.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);
                    buffer.append(ch);
                    lastPos = pos + 6;
                } else {
                    ch = (char) Integer.parseInt(src.substring(pos + 1, pos + 3), 16);
                    buffer.append(ch);
                    lastPos = pos + 3;
                }
            } else {
                if (pos == -1) {
                    buffer.append(src.substring(lastPos));
                    lastPos = src.length();
                } else {
                    buffer.append(src, lastPos, pos);
                    lastPos = pos;
                }
            }
        }
        return buffer.toString();
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章