URLENcode 判断字符集格式 UTF8,GBK

本文介绍了URL编码的原理及常见编码方式,并通过实例演示了如何使用Java进行URL的编码与解码操作,同时对比了UTF-8和GBK两种编码在URL中的应用。

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])+$");

	
}


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

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

输出日志:

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

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

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

可以看看字符集那块。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

bohu83

买个馒头吃

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值