dev-c++ .c 源码 编码 ansi_URLEncoder.encode 源码解析

URLEncoder是HTML表单编码的实用程序类,此类包含用于将String转换为application/x-www-form-urlencodedMIME格式的静态方法。有关HTML表单编码的详细信息,可以参阅HTMLspecification。

在对字符串进行转义时,会遵循以下规则:

  • 字母数字字符“ a ”到“ z ”,“ A ”到“ Z ”和“ 0 ”到“ 9 ”保持不变。
  • 特殊字符“ . ”,“ - ”,“ * ”和“ _ ”保持不变。
  • 空格字符“”被转换为加号“ + ”。
  • 所有其他字符都是不安全的,并且首先使用某种编码方案将其转换为一个或多个字节。 然后每个字节由3个字符的字符串“ %xy ”表示,其中xy是字节的两位十六进制表示。 建议使用的编码方案是UTF-8。 但是,出于兼容性原因,如果未指定编码,则使用平台的默认编码。

目前该类包含两个方法:

50297f5ebe5c5644d4a8c4a04fb11e25.png

源码说明:

public class URLEncoder {

    /**
     * 安全字符set集合
     */
    static BitSet dontNeedEncoding;
    static final int caseDiff = ('a' - 'A');
    /**
     * 系统默认编码
     */
    static String dfltEncName = null;

    static {

        /* The list of characters that are not encoded has been
         * determined as follows:
         *
         * RFC 2396 states:
         * -----
         * Data characters that are allowed in a URI but do not have a
         * reserved purpose are called unreserved.  These include upper
         * and lower case letters, decimal digits, and a limited set of
         * punctuation marks and symbols.
         *
         * unreserved  = alphanum | mark
         *
         * mark        = "-" | "_" | "." | "!" | "~" | "*" | "'" | "(" | ")"
         *
         * Unreserved characters can be escaped without changing the
         * semantics of the URI, but this should not be done unless the
         * URI is being used in a context that does not allow the
         * unescaped character to appear.
         * -----
         *
         * It appears that both Netscape and Internet Explorer escape
         * all special characters from this list with the exception
         * of "-", "_", ".", "*". While it is not clear why they are
         * escaping the other characters, perhaps it is safest to
         * assume that there might be contexts in which the others
         * are unsafe if not escaped. Therefore, we will use the same
         * list. It is also noteworthy that this is consistent with
         * O'Reilly's "HTML: The Definitive Guide" (page 164).
         *
         * As a last note, Intenet Explorer does not encode the "@"
         * character which is clearly not unreserved according to the
         * RFC. We are being consistent with the RFC in this matter,
         * as is Netscape.
         *
         */

        dontNeedEncoding = new BitSet(256);
        int i;
        for (i = 'a'; i <= 'z'; i++) {
            dontNeedEncoding.set(i);
        }
        for (i = 'A'; i <= 'Z'; i++) {
            dontNeedEncoding.set(i);
        }
        for (i = '0'; i <= '9'; i++) {
            dontNeedEncoding.set(i);
        }
        dontNeedEncoding.set(' ');
        dontNeedEncoding.set('-');
        dontNeedEncoding.set('_');
        dontNeedEncoding.set('.');
        dontNeedEncoding.set('*');

        dfltEncName = AccessController.doPrivileged(
                new GetPropertyAction("file.encoding")
        );
    }

    /**
     * 私有的构造方法
     */
    private URLEncoder() { }

    /**
     * 将字符串转换成<code> x-www-form-urlencoded </ code>格式。
     * 此方法使用平台的默认编码
     *
     * @param   s   需要进行转换的字符串.
     * @deprecated
     * @return
     */
    @Deprecated
    public static String encode(String s) {

        String str = null;

        try {
            str = encode(s, dfltEncName);
        } catch (UnsupportedEncodingException e) {
            // The system should always have the platform default
        }

        return str;
    }

    /**
     * 将字符串转换成<code> application / x-www-form-urlencoded </ code>格式。
     * 此方法使用指定的编码进行转换
     *
     * <em> <strong>注意</ strong>:<a href ="http://www.w3.org/TR/html40/appendix/notes.html#non-ascii-chars”>
     * 万维网联盟建议应该使用UTF-8。 不这样做可能会引入不兼容的东西。</ em>
     *
     * @param   s   需要进行转换的字符串.
     * @param   enc   字符串编码格式.
     * @return
     * @exception  UnsupportedEncodingException
     *             If the named encoding is not supported
     * @see URLDecoder#decode(java.lang.String, java.lang.String)
     * @since 1.4
     */
    public static String encode(String s, String enc)
            throws UnsupportedEncodingException {

        //标识是否有需要转义的字符
        boolean needToChange = false;
        //最终返回的字符串
        StringBuffer out = new StringBuffer(s.length());
        //系统编码
        Charset charset;
        //转义字符拼接
        CharArrayWriter charArrayWriter = new CharArrayWriter();

        if (enc == null)
            throw new NullPointerException("charsetName");

        try {
            charset = Charset.forName(enc);
        } catch (IllegalCharsetNameException e) {
            throw new UnsupportedEncodingException(enc);
        } catch (UnsupportedCharsetException e) {
            throw new UnsupportedEncodingException(enc);
        }

        for (int i = 0; i < s.length();) {
            int c = (int) s.charAt(i);

            if (dontNeedEncoding.get(c)) {
                //如果是安全字符,则直接进行拼接
                if (c == ' ') {
                    c = '+';
                    needToChange = true;
                }
                //System.out.println("Storing: " + c);
                out.append((char)c);
                i++;
            } else {
                // convert to external encoding before hex conversion
                do {
                    charArrayWriter.write(c);
                    /*
                     * 处理特殊区段内的编码
                     */
                    if (c >= 0xD800 && c <= 0xDBFF) {
                        /*
                          System.out.println(Integer.toHexString(c)
                          + " is high surrogate");
                        */
                        if ( (i+1) < s.length()) {
                            int d = (int) s.charAt(i+1);
                            /*
                              System.out.println("tExamining "
                              + Integer.toHexString(d));
                            */
                            if (d >= 0xDC00 && d <= 0xDFFF) {
                                /*
                                  System.out.println("t"
                                  + Integer.toHexString(d)
                                  + " is low surrogate");
                                */
                                charArrayWriter.write(d);
                                i++;
                            }
                        }
                    }
                    i++;
                } while (i < s.length() && !dontNeedEncoding.get((c = (int) s.charAt(i))));

                charArrayWriter.flush();
                String str = new String(charArrayWriter.toCharArray());
                //使用指定编码编译
                byte[] ba = str.getBytes(charset);
                //开始拼接转义字符
                for (int j = 0; j < ba.length; j++) {
                    out.append('%');
                    char ch = Character.forDigit((ba[j] >> 4) & 0xF, 16);
                    // converting to use uppercase letter as part of
                    // the hex value if ch is a letter.
                    if (Character.isLetter(ch)) {
                        ch -= caseDiff;
                    }
                    out.append(ch);
                    ch = Character.forDigit(ba[j] & 0xF, 16);
                    if (Character.isLetter(ch)) {
                        ch -= caseDiff;
                    }
                    out.append(ch);
                }
                charArrayWriter.reset();
                needToChange = true;
            }
        }

        return (needToChange? out.toString() : s);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值