package cn.struts.util;
import java.util.Arrays;
/**
* 字符编码
*/
public class URLEnCodeing {
private static final char[] c = { '\\', '/', ':', '?', '&'};
/**
* URL 编码 http://localhost:8080/webproject/中国测试
*
* @param url http://localhost:8080/webproject/%4e2d%56fd%6d4b%8bd5
*
* @return
*/
public static String escape(String url) {
int length = url.length();
StringBuilder sb = new StringBuilder(length);
char currentChar;
for (int i = 0; i < length; i++) {
// 当前字符是不是数字,或字母,特殊字符'\\', '/', ':'
currentChar = url.charAt(i);
if(currentChar == 37)
throw new RuntimeException("不能是%");
if (currentChar <= 127) {
sb.append(currentChar);
} else {
sb.append("%");
sb.append(Integer.toString(currentChar, 16));
}
}
return sb.toString();
}
/**
* URL 编码 http://localhost:8080/webproject/中国测试
*
* @param url http://localhost:8080/webproject/%4e2d%56fd%6d4b%8bd5?time=11234566&name=%4e16%754c
*
* @return
*/
public static String unEscape(String url) {
int length = url.length();
StringBuilder sb = new StringBuilder(length);
String[] str = url.split("%");
sb.append(str[0]);
// %4e2d //"8bd5?time=11234566&name="
for (int i = 1; i < str.length; i++) {
String s = str[i];
if(s.length() > 4){
sb.append((char)Integer.parseInt(s.substring(0, 4), 16));
sb.append(s.substring(4));
}else
sb.append((char) Integer.parseInt(str[i], 16));
}
return sb.toString();
}
public static void main(String[] args) {
String value = "http://localhost:8080/webpr&oject/中国测试?time=11234566&name=世界";
String url = "http://localhost:8080/webp25r&oject/%4e2d%56fd%6d4b%8bd5?time=11234566&name=%4e16%754c";
System.out.println(URLEnCodeing.escape(value));
System.out.println(URLEnCodeing.unEscape(url));
System.out.println(Integer.toString((char)'%',16));
}
}