浏览器地址栏编码

public class CodingUtil {
	
	public static String decode(String query) throws Exception {
		if (query == null)
			return null;

		String utfStr = java.net.URLDecoder.decode(query, "UTF-8");
		String gbkStr = java.net.URLDecoder.decode(query, "GBK");

		boolean encoded = (query.equals(utfStr));
		if (encoded) {
			utfStr = new String(query.getBytes("ISO-8859-1"), "UTF-8");
			gbkStr = new String(query.getBytes("ISO-8859-1"), "GBK");
		}
		String src = null;
		boolean isUTF = isUTF(utfStr.getBytes("UTF-8")); // java.util.Arrays.equals(utfStr.getBytes("UTF-8")
		boolean isGBK = isGBK(gbkStr.getBytes("GBK"));// gbkStr.getBytes("GBK"));
		if (isUTF && (!isGBK)) {
			src = utfStr;
		} else {
			src = gbkStr;
		}
		return src;
	}
	
	static int L1 = 0x80;// ascii,UFT8可用1-6个字节编码,ASCII用一个字节
	static int L2 = 0xC0;
	static int L3 = 0xE0;
	static int L4 = 0xF0;
	static int LS = 0x80;
	
	private static boolean isUTF(byte[] bytes) {
		for (int i = 0; i < bytes.length;) {
			int b = getInt(bytes[i]);
			if ((L1 & b) == 0x00) {
				i++;
			} else if ((L4 & b) == L4 && (getInt(bytes[i + 1]) & LS) == LS
					&& (getInt(bytes[i + 2]) & LS) == LS
					&& (getInt(bytes[i + 3]) & LS) == LS) {
				i += 4;
			} else if ((L3 & b) == L3 && (getInt(bytes[i + 1]) & LS) == LS
					&& (getInt(bytes[i + 2]) & LS) == LS) {
				i += 3;
			} else if ((L2 & b) == L2 && (getInt(bytes[i + 1]) & LS) == LS) {
				i += 2;
			} else {
				System.out.println(" ====>" + i);
				return false;
			}
		}
		return true;
	}
	
	private static int getInt(byte b) {
		return b & 0xFF;
	}
	
	static int GBK_START = 0x8140;
	static int GBK_END = 0xFEFE;
	
	private static boolean isGBK(byte[] bytes) {

		for (int i = 0; i < bytes.length;) {

			if (i + 2 > bytes.length)
				return false;

			int b = getInt(bytes[i]);
			if ((L1 & b) == 0x00) {
				i++;
				continue;
			}

			int high = b << 8;
			int c = high + getInt(bytes[i + 1]);
			if (c < GBK_START || c > GBK_END) {
				return false;
			}
			i += 2;
		}
		return true;
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值