URL编码 百分号编码 URLDecoder.decode的大致实现原理
package com.dt.test;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
/***
* URL编码又叫百分号编码 URLDecoder.decode的大致实现原理
*/
class testURLEncode {
public void testURLEncode() {
String testString;
try {
testString = URLEncoder.encode("中文", "utf-8");
System.out.println("testString : " + testString);
testString = testString.replace("%", "");
int length = testString.length() / 2;
byte[] data = new byte[length];
for (int i = 0; i < length; i++) {
data[i] = (byte) Integer.parseInt(testString.substring(2 * i,
2 * i + 2), 16);
}
String result = new String(data, "utf-8");
System.out.println("result : " + result);
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
public void testURLEncodeGBK() {
String testString;
String testString0;
try {
testString = URLEncoder.encode("中文", "utf-8");
testString0 = testString;
System.out.println("testString : " + testString);
testString = URLDecoder.decode(testString0,"GBK");
System.out.println("decode : " + testString);
testString = URLDecoder.decode(testString0,"utf-8");
System.out.println("decode : " + testString);
testString = URLEncoder.encode("中文", "GBK");
System.out.println("decode : " + testString);
testString = URLDecoder.decode(testString,"GBK");
System.out.println("decode : " + testString);
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
public static void main(String[] args) {
new testURLEncode().testURLEncode();
new testURLEncode().testURLEncodeGBK();
}
}
testString : %E4%B8%AD%E6%96%87
result : 中文
testString : %E4%B8%AD%E6%96%87
decode : 涓枃
decode : 中文
decode : %D6%D0%CE%C4
decode : 中文