End

URL编码 URLEncoder 示例

2016-12-27
对字符编码时的规则
通常如果一样东西需要编码,说明这样东西并不适合传输。原因多种多样,如Size过大,包含隐私数据。
对于Url来说,之所以要进行编码,一个是因为Url中有些字符会引起歧义。 
例如Url参数字符串中使用key=value键值对这样的形式来传参,键值对之间以&符号分隔,如/s?q=abc&ie=utf-8。如果你的value字符串中包含了=或者&,那么势必会造成接收Url的服务器解析错误,因此必须将引起歧义的&和=符号进行转义,也就是对其进行编码
另外,Url的编码格式采用的是ASCII码,而不是Unicode(包含中文),这也就是说你不能在Url中包含任何非ASCII字符,例如中文。否则如果客户端浏览器和服务端浏览器支持的字符集不同的情况下,中文可能会造成问题。

编码时的规则:
  • 【字母】字符 "a" 到 "z"、"A" 到 "Z" 和【数字】字符 "0" 到 "9" 保持不变
  • 特殊字符【.】【-】【*】【_】保持不变
  • 空格字符 【 】转换为一个加号【+】
  • 所有其他字符都是不安全的,因此首先使用一些编码机制将它们转换为【一个或多个】字节,然后每个字节用一个包含 3 个字符的字符串【%xy】表示,其中 xy 为该字节的两位十六进制表示形式。
  • 可以指定对这些字符进行解码的编码机制,或者如果未指定的话,则使用平台的默认编码机制。

例如,使用 UTF-8 编码机制,字符串【ü@】将转换为【%C3%BC%40】,因为在 UTF-8 中,字符【ü】编码为两个字节【0xC3和0xBC】,字符【@】编码为一个字节【0x40】。
 

解码时的规则:
  • 将把【%xy】格式的子序列视为【一个字节】,其中 xy 为 8 位的两位十六进制表示形式。
  • 然后,所有连续包含一个或多个这些字节序列的子字符串,将被其编码可生成这些连续字节的字符所代替。
     
测试代码
public class Test {
    public static void main(String[] args) throws Exception {
        String enc = "UTF-8";
        test("aA0 .-*_", enc);//编码【aA0+.-*_】解码【aA0 .-*_】
        test("@", enc);//编码【%40】解码【@】
        test("ü", enc);//编码【%C3%BC】解码【ü】
        test("白", enc);//编码【%E7%99%BD】解码【白】
        test("白""GBK");//编码【%B0%D7】解码【白】
    }
    /**
     * 测试编解码
     * @param str    原始字符串
     * @param enc    对字符串进行URLEncoder和URLDecoder时使用的编码规则
     * @throws UnsupportedEncodingException
     */
    public static void test(String str, String enc) throws UnsupportedEncodingException {
        String encode = URLEncoder.encode(str, enc);//推荐 UTF-8。如果未指定,则使用平台的默认编码
        String decode = URLDecoder.decode(encode, enc);//编码和解码必须使用同一套码表,否则解码时可能乱码
        System.out.println("原始字符串【" + str + "】编码后【" + encode + "】解码后【" + decode + "】");
        //获取通过UTF8码表编码的字符串的字节数组
        byte[] bytes = str.getBytes(enc);
        System.out.println("        原始字符串对应的字节数组" + Arrays.toString(bytes));
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            //手动对【每个字节】都进行上面【类似URLEncoder】编码规则的算法进行编码(即使字母和数字也进行了编码)
            sb.append(Integer.toHexString(b & 0xFF).toUpperCase() + " ");
        }
        System.out.println("        对每个字节都进行编码【" + sb.toString().trim() + "】");
    }
    //源码
    public static String decode(String s, String enc) throws UnsupportedEncodingException {
        boolean needToChange = false;
        int numChars = s.length();//字符数
        StringBuffer sb = new StringBuffer(numChars > 500 ? numChars / 2 : numChars);
        int i = 0;
        if (enc.length() == 0) throw new UnsupportedEncodingException("URLDecoder: empty string enc parameter");
        char c;
        byte[] bytes = null;
        while (i < numChars) {
            c = s.charAt(i);//逐个遍历所有字符
            switch (c) {
            case '+':
                sb.append(' ');
                i++;
                needToChange = true;
                break;
            case '%':
                try {
                    if (bytes == null) bytes = new byte[(numChars - i) / 3];// (numChars-i)/3 is an upper bound上线 for the number of remaining剩下的 bytes
                    int pos = 0;
                    while (((i + 2) < numChars) && (c == '%')) {
                        int v = Integer.parseInt(s.substring(i + 1, i + 3), 16);//16进制
                        if (v < 0) throw new IllegalArgumentException("URLDecoder: Illegal hex characters in escape (%) pattern - negative value");
                        bytes[pos++] = (byte) v;
                        i += 3;
                        if (i < numChars) c = s.charAt(i);
                    }
                    // A trailing, incomplete不完全的 byte encoding such as "%x" will cause an exception to be thrown
                    if ((i < numChars) && (c == '%')) throw new IllegalArgumentException("URLDecoder: Incomplete trailing escape (%) pattern");
                    sb.append(new String(bytes, 0, pos, enc));
                } catch (NumberFormatException e) {
                    throw new IllegalArgumentException("URLDecoder: Illegal hex characters in escape (%) pattern - " + e.getMessage());
                }
                needToChange = true;
                break;
            default:
                sb.append(c);
                i++;
                break;
            }
        }
        return (needToChange ? sb.toString() : s);
    }
}





posted @ 2016-12-27 14:00  白乾涛  阅读(4971)  评论(0编辑  收藏  举报