18:%E6%B5%8B%E8%AF%95
12:%B2%E2%CA%D4
测试
测试
����
测试
URL编码的字符集是ascII码。我们常见的汉字跟特殊字符就需要特殊处理。
场景:
搜索引擎:
https://www.baidu.com/s?word=%E6%B5%8B%E8%AF%95
这个就是“”测试“”的编码
public class EncodeTest {
public static void main(String[] args) throws UnsupportedEncodingException {
// TODO Auto-generated method stub
String encodeStr = URLEncoder.encode("测试", "UTF-8");
System.out.println(encodeStr.length()+":"+encodeStr);
String encodeStr2 = URLEncoder.encode("测试", "GBK");
System.out.println(encodeStr2.length()+":"+encodeStr2);
String decodeStr = URLDecoder.decode(encodeStr, "UTF-8");
System.out.println(decodeStr);
String decodeStr2 = URLDecoder.decode(encodeStr2, "GBK");
System.out.println(decodeStr2);
String decodeStr3 = URLDecoder.decode(encodeStr2, "UTF-8");
System.out.println(decodeStr3);
String type = getEncoding(encodeStr2);
String decodeStr4 = URLDecoder.decode(encodeStr2, type);
System.out.println(decodeStr4);
}
private static String getEncoding(String str) {
// TODO Auto-generated method stub
Matcher publicMatcher = publicPattern.matcher(str);
if(publicMatcher.matches()) {
return "GBK";
}
Matcher matcher = utf8Pattern.matcher(str);
if (matcher.matches()) {
return "UTF-8";
} else {
return "GBK";
}
}
protected static final Pattern utf8Pattern = Pattern.compile("^([\\x01-\\x7f]|[\\xc0-\\xdf][\\x80-\\xbf]|[\\xe0-\\xef][\\x80-\\xbf]{2}|[\\xf0-\\xf7][\\x80-\\xbf]{3}|[\\xf8-\\xfb][\\x80-\\xbf]{4}|[\\xfc-\\xfd][\\x80-\\xbf]{5})+$");
protected static final Pattern publicPattern = Pattern.compile("^([\\x01-\\x7f]|[\\xc0-\\xdf][\\x80-\\xbf])+$");
}
有的时候,我们不知道编码方式是什么,可以采用上面例子的方法。常见的就是utf-8,gbk
输出日志:
18:%E6%B5%8B%E8%AF%95
12:%B2%E2%CA%D4
测试
测试
����
测试
如果字符集一直,可以正常的decode输出。
还可以看出:utf的编码时占用了3个字节(常用的,个别汉字也有占2个字节的),gbk是2个字节。
可以看看字符集那块。
本文介绍了URL编码的原理及常见编码方式,并通过实例演示了如何使用Java进行URL的编码与解码操作,同时对比了UTF-8和GBK两种编码在URL中的应用。

374

被折叠的 条评论
为什么被折叠?



