public class EscapeUnescape {</p><p>public static String escape(String src) {<br /> int i;<br /> char j;<br /> StringBuffer tmp = new StringBuffer();<br /> tmp.ensureCapacity(src.length() * 6);<br /> for (i = 0; i < src.length(); i++) {<br /> j = src.charAt(i);<br /> if (Character.isDigit(j) || Character.isLowerCase(j)<br /> || Character.isUpperCase(j))<br /> tmp.append(j);<br /> else if (j < 256) {<br /> tmp.append("%");<br /> if (j < 16)<br /> tmp.append("0");<br /> tmp.append(Integer.toString(j, 16));<br /> } else {<br /> tmp.append("%u");<br /> tmp.append(Integer.toString(j, 16));<br /> }<br /> }<br /> return tmp.toString();<br />}</p><p>public static String unescape(String src) {<br /> if(src == null)return null;<br /> StringBuffer tmp = new StringBuffer();<br /> tmp.ensureCapacity(src.length());<br /> int lastPos = 0, pos = 0;<br /> char ch;<br /> while (lastPos < src.length()) {<br /> pos = src.indexOf("%", lastPos);<br /> if (pos == lastPos) {<br /> if (src.charAt(pos + 1) == 'u') {<br /> ch = (char) Integer.parseInt(src<br /> .substring(pos + 2, pos + 6), 16);<br /> tmp.append(ch);<br /> lastPos = pos + 6;<br /> } else if (src.charAt(pos + 1) == ' '<br /> || src.charAt(pos + 1) == ';') {<br /> tmp.append(src.substring(pos, pos + 1));<br /> lastPos = pos + 1;<br /> } else {<br /> ch = (char) Integer.parseInt(src<br /> .substring(pos + 1, pos + 3), 16);<br /> tmp.append(ch);<br /> lastPos = pos + 3;<br /> }<br /> } else {<br /> if (pos == -1) {<br /> tmp.append(src.substring(lastPos));<br /> lastPos = src.length();<br /> } else {<br /> tmp.append(src.substring(lastPos, pos));<br /> lastPos = pos;<br /> }<br /> }<br /> }<br /> return tmp.toString();<br />}</p><p>public static void main(String[] args) {<br /> String tmp = "中文";<br /> System.out.println("testing escape : " + tmp);<br /> tmp = escape(tmp);<br /> System.out.println(tmp);<br /> System.out.println("testing unescape :" + tmp);<br /> System.out.println(unescape("%u6211%u4eec"));<br />}<br />}<br />