[quote]
[img]http://anzhoujava.iteye.com/upload/picture/pic/67077/729b559b-0f76-36b6-86b6-60dd30900d32.jpg[/img]
package com.java.unit;
import java.io.ByteArrayOutputStream;
public class StringUtil {
private static final String VERIABLY =
"abcdefghijklmnopqrstuvwxyz"+
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"+
".-*_";
public static String urlEncode(
String s, String charset) throws Exception {
// abc
byte[] bytes =
s.getBytes(charset);
StringBuilder sb = new StringBuilder();
outer:
for(int i=0;i byte b = bytes[i];
if(b == ' ') {
sb.append('+');
continue outer;
}
for(int j=0;j if(VERIABLY.charAt(j) == b) {
sb.append((char) b);
continue outer;
}
}
String hex = Integer.toHexString(b&0x000000ff);
if(hex.length() == 1) hex = '0'+hex;
hex = '%'+hex;
sb.append(hex);
}
return sb.toString();
}
public static String urlDecode(String s,String charset) throws Exception {
ByteArrayOutputStream out =
new ByteArrayOutputStream();
for(int i=0;i char c = s.charAt(i);
if(c == '%') {
// %f8
String hex = "";
hex += s.charAt(++i);
hex += s.charAt(++i);
int n = Integer.parseInt(hex, 16);
out.write(n);
} else {
if(VERIABLY.indexOf(c) != -1) {
out.write(c);
continue;
}
if('+' == c) {
out.write(' ');
continue;
}
}
}
byte[] data = out.toByteArray();
return new String(data,charset);
}
public static void main(String[] args) throws Exception {
String s = urlEncode("游戏","UTF-8");
System.out.println(s);
s = urlDecode("%e6%b8%b8%e6%88%8f", "UTF-8");
System.out.println(s);
}
}
[/quote]