瀏覽器地址欄編碼

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;
	}
}

發佈了22 篇原創文章 · 獲贊 2 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章