Android URL encode 空格处理

         在应用程序开发过程中或多或少的需要通过HTTP、HTTPS协议与服务器交互。这其中一个常见的情况就是要求对URL进行encode处理,以保证中文、特殊字符的正确传递。不过这个小小的url encode方法有些时候也会酿成"血案"。

         今天在Android开发中做一个商户搜索功能时碰到一个问题,用户有些时候可以需要通过多个关键字进行搜索,多个关键字之间用空格分隔,客户端通过http get去请求服务器数据,有经验的开发人员都知道此时需要对URL进行编码,很自然的通过URLEncoder.encode(input, "UTF-8")方法进行URL编码,但是Server却不能正确识别。平时开发一直都是这么用啊,怎么就不行呢?困惑的同时也一步一步的debug代码,最后发现URL中的空格符(ASCII码是0x20),在经过java.net.URLEncoder类encode以后,会变成+号,而不是%20,从而造成了server不能正确识别。

然后自己去看了一眼JDK中 URLEncoder.encode(String s, String enc) 源码,这里给大家贴一下:

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);
            //System.out.println("Examining character: " + c);
            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 this character represents the start of a Unicode
                     * surrogate pair, then pass in two characters. It's not
                     * clear what should be done if a bytes reserved in the
                     * surrogate pairs range occurs outside of a legal
                     * surrogate pair. For now, just treat it as if it were
                     * any other character.
                     */
                    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);
    }

这里dontNeedEncoding的初始化是在静态代码块中完成的,如下:

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(' '); /* encoding a space to a + is done
                                    * in the encode() method */
        dontNeedEncoding.set('-');
        dontNeedEncoding.set('_');
        dontNeedEncoding.set('.');
        dontNeedEncoding.set('*');

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

看到这里,自己也就明白了,URLEncoder.encode(String s, String enc) 会将空格编码为“+”,原文:encoding a space to a + is done in the encode() method。当然,这是符合URL规范的,见RFC-1738。

那么要想将空格符编码为%20,怎么办呢?Android SDK为我们提供了 android.net.Uri类完成此功能,该类使用RFC-2396标准。语法如下:

static String encode(String s, String allow)
Encodes characters in the given string as '%'-escaped octets using the UTF-8 scheme.
static String encode(String s)
Encodes characters in the given string as '%'-escaped octets using the UTF-8 scheme.


示例代码如下:

//1、JDK中URLEncoder encode实现
		String input = "肯德基 柳芳";
		try {
			String urlEncode = URLEncoder.encode(input, "UTF-8");
			System.out.println("urlEncode="+urlEncode);
			
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		//2、Android中Uri encode实现
		String input = "肯德基 柳芳";
		String urlEncode = Uri.encode(input);
		System.out.println("urlEncode="+urlEncode);


输出结果:

urlEncode=%E8%82%AF%E5%BE%B7%E5%9F%BA+%E6%9F%B3%E8%8A%B3
urlEncode=%E8%82%AF%E5%BE%B7%E5%9F%BA%20%E6%9F%B3%E8%8A%B3


      关于Url、Uri的区别可以参考IBM developerworks上的一篇文章:分清 URI、URL 和 URN和百度百科上的介绍




你可能感兴趣的:(Android)