URLENcode 判断字符集格式 UTF8,GBK

来源:互联网 发布:java分布式框架 dubbo 编辑:程序博客网 时间:2024/05/17 07:25

18:%E6%B5%8B%E8%AF%9512:%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 stubMatcher 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])+$");}


比如我们有一份上网日志,包含了一份包含关键字的url日志,

有的时候,我们不知道编码方式是什么,可以采用上面例子的方法。常见的就是utf-8,gbk

输出日志:

18:%E6%B5%8B%E8%AF%9512:%B2%E2%CA%D4测试测试����测试

如果字符集一直,可以正常的decode输出。

还可以看出:utf的编码时占用了3个字节(常用的,个别汉字也有占2个字节的),gbk是2个字节。

可以看看字符集那块。


原创粉丝点击