| 
                         最近需要将一些python代码转成java,遇到url编码 
urllib.quote(str,safe='/') 
但java中URLEncoder.encode(arg,Constant.UTF_8)会将'/'转成%2F 
网上查了一下 java没见到类似的safe方式,只好自己实现一个类 
<span style="color: #0000ff;">public <span style="color: #0000ff;">class<span style="color: #000000;"> UrlSafeEncoder {
</span><span style="color: #0000ff;">static</span><span style="color: #000000;"> BitSet dontNeedEncoding;
</span><span style="color: #0000ff;">static</span> <span style="color: #0000ff;">final</span> <span style="color: #0000ff;">int</span> caseDiff = ('a' - 'A'<span style="color: #000000;">);
</span><span style="color: #0000ff;">static</span> String dfltEncName = <span style="color: #0000ff;">null</span><span style="color: #000000;">;
</span><span style="color: #0000ff;">static</span><span style="color: #000000;"> {
    </span><span style="color: #008000;">/*</span><span style="color: #008000;"> 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.
     *
     </span><span style="color: #008000;">*/</span><span style="color: #000000;">
    dontNeedEncoding </span>= <span style="color: #0000ff;">new</span> BitSet(256<span style="color: #000000;">);
    </span><span style="color: #0000ff;">int</span><span style="color: #000000;"> i;
    </span><span style="color: #0000ff;">for</span> (i = 'a'; i <= 'z'; i++<span style="color: #000000;">) {
        dontNeedEncoding.set(i);
    }
    </span><span style="color: #0000ff;">for</span> (i = 'A'; i <= 'Z'; i++<span style="color: #000000;">) {
        dontNeedEncoding.set(i);
    }
    </span><span style="color: #0000ff;">for</span> (i = '0'; i <= '9'; i++<span style="color: #000000;">) {
        dontNeedEncoding.set(i);
    }
    dontNeedEncoding.set(</span>' '); <span style="color: #008000;">/*</span><span style="color: #008000;"> encoding a space to a + is done
                                * in the encode() method </span><span style="color: #008000;">*/</span><span style="color: #000000;">
    dontNeedEncoding.set(</span>'-'<span style="color: #000000;">);
    dontNeedEncoding.set(</span>'_'<span style="color: #000000;">);
    dontNeedEncoding.set(</span>'.'<span style="color: #000000;">);
    dontNeedEncoding.set(</span>'*'<span style="color: #000000;">);
    dfltEncName </span>=<span style="color: #000000;"> AccessController.doPrivileged(
        </span><span style="color: #0000ff;">new</span> GetPropertyAction("file.encoding"<span style="color: #000000;">)
    );
}
</span><span style="color: #008000;">/**</span><span style="color: #008000;">
 * You can't call the constructor.
 </span><span style="color: #008000;">*/</span>
<span style="color: #0000ff;">private</span><span style="color: #000000;"> UrlSafeEncoder() { }
</span><span style="color: #008000;">/**</span><span style="color: #008000;">
 * Translates a string into {</span><span style="color: #808080;">@code</span><span style="color: #008000;"> application/x-www-form-urlencoded}
 * format using a specific encoding scheme. This method uses the
 * supplied encoding scheme to obtain the bytes for unsafe
 * characters.
 * <p>
 * <em><strong>Note:</strong> The <a href=
 * "</span><span style="color: #008000; text-decoration: underline;">http://www.w3.org/TR/html40/appendix/notes.html</span><span style="color: #008000;">#non-ascii-chars">
 * World Wide Web Consortium Recommendation</a> states that
 * UTF-8 should be used. Not doing so may introduce
 * incompatibilities.</em>
 *
 * </span><span style="color: #808080;">@param</span><span style="color: #008000;">   s   {</span><span style="color: #808080;">@code</span><span style="color: #008000;"> String} to be translated.
 * </span><span style="color: #808080;">@param</span><span style="color: #008000;">   enc   The name of a supported
 *    <a href="../lang/package-summary.html#charenc">character
 *    encoding</a>.
 * </span><span style="color: #808080;">@return</span><span style="color: #008000;">  the translated {</span><span style="color: #808080;">@code</span><span style="color: #008000;"> String}.
 * </span><span style="color: #808080;">@exception</span><span style="color: #008000;">  UnsupportedEncodingException
 *             If the named encoding is not supported
 * </span><span style="color: #808080;">@see</span><span style="color: #008000;"> URLDecoder#decode(java.lang.String,java.lang.String)
 * </span><span style="color: #808080;">@since</span><span style="color: #008000;"> 1.4
 </span><span style="color: #008000;">*/</span>
<span style="color: #0000ff;">public</span> <span style="color: #0000ff;">static</span> String encode(String s,String enc,<span style="color: #0000ff;">char</span><span style="color: #000000;"> safe)
    </span><span style="color: #0000ff;">throws</span><span style="color: #000000;"> UnsupportedEncodingException {
    dontNeedEncoding.set(safe);
    </span><span style="color: #0000ff;">boolean</span> needToChange = <span style="color: #0000ff;">false</span><span style="color: #000000;">;
    StringBuffer out </span>= <span style="color: #0000ff;">new</span><span style="color: #000000;"> StringBuffer(s.length());
    Charset charset;
    CharArrayWriter charArrayWriter </span>= <span style="color: #0000ff;">new</span><span style="color: #000000;"> CharArrayWriter();
    </span><span style="color: #0000ff;">if</span> (enc == <span style="color: #0000ff;">null</span><span style="color: #000000;">)
        </span><span style="color: #0000ff;">throw</span> <span style="color: #0000ff;">new</span> NullPointerException("charsetName"<span style="color: #000000;">);
    </span><span style="color: #0000ff;">try</span><span style="color: #000000;"> {
        charset </span>=<span style="color: #000000;"> Charset.forName(enc);
    } </span><span style="color: #0000ff;">catch</span><span style="color: #000000;"> (IllegalCharsetNameException e) {
        </span><span style="color: #0000ff;">throw</span> <span style="color: #0000ff;">new</span><span style="color: #000000;"> UnsupportedEncodingException(enc);
    } </span><span style="color: #0000ff;">catch</span><span style="color: #000000;"> (UnsupportedCharsetException e) {
        </span><span style="color: #0000ff;">throw</span> <span style="color: #0000ff;">new</span><span style="color: #000000;"> UnsupportedEncodingException(enc);
    }
    </span><span style="color: #0000ff;">for</span> (<span style="color: #0000ff;">int</span> i = 0; i <<span style="color: #000000;"> s.length();) {
        </span><span style="color: #0000ff;">int</span> c = (<span style="color: #0000ff;">int</span><span style="color: #000000;">) s.charAt(i);
        </span><span style="color: #008000;">//</span><span style="color: #008000;">System.out.println("Examining character: " + c);</span>
        <span style="color: #0000ff;">if</span><span style="color: #000000;"> (dontNeedEncoding.get(c)) {
            </span><span style="color: #0000ff;">if</span> (c == ' '<span style="color: #000000;">) {
                c </span>= '+'<span style="color: #000000;">;
                needToChange </span>= <span style="color: #0000ff;">true</span><span style="color: #000000;">;
            }
            </span><span style="color: #008000;">//</span><span style="color: #008000;">System.out.println("Storing: " + c);</span>
            out.append((<span style="color: #0000ff;">char</span><span style="color: #000000;">)c);
            i</span>++<span style="color: #000000;">;
        } </span><span style="color: #0000ff;">else</span><span style="color: #000000;"> {
            </span><span style="color: #008000;">//</span><span style="color: #008000;"> convert to external encoding before hex conversion</span>
            <span style="color: #0000ff;">do</span><span style="color: #000000;"> {
                charArrayWriter.write(c);
                </span><span style="color: #008000;">/*</span><span style="color: #008000;">
                 * 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.
                 </span><span style="color: #008000;">*/</span>
                <span style="color: #0000ff;">if</span> (c >= 0xD800 && c <= 0xDBFF<span style="color: #000000;">) {
                    </span><span style="color: #008000;">/*</span><span style="color: #008000;">
                      System.out.println(Integer.toHexString(c)
                      + " is high surrogate");
                    </span><span style="color: #008000;">*/</span>
                    <span style="color: #0000ff;">if</span> ( (i+1) <<span style="color: #000000;"> s.length()) {
                        </span><span style="color: #0000ff;">int</span> d = (<span style="color: #0000ff;">int</span>) s.charAt(i+1<span style="color: #000000;">);
                        </span><span style="color: #008000;">/*</span><span style="color: #008000;">
                          System.out.println("tExamining "
                          + Integer.toHexString(d));
                        </span><span style="color: #008000;">*/</span>
                        <span style="color: #0000ff;">if</span> (d >= 0xDC00 && d <= 0xDFFF<span style="color: #000000;">) {
                            </span><span style="color: #008000;">/*</span><span style="color: #008000;">
                              System.out.println("t"
                              + Integer.toHexString(d)
                              + " is low surrogate");
                            </span><span style="color: #008000;">*/</span><span style="color: #000000;">
                            charArrayWriter.write(d);
                            i</span>++<span style="color: #000000;">;
                        }
                    }
                }
                i</span>++<span style="color: #000000;">;
            } </span><span style="color: #0000ff;">while</span> (i < s.length() && !dontNeedEncoding.get((c = (<span style="color: #0000ff;">int</span><span style="color: #000000;">) s.charAt(i))));
            charArrayWriter.flush();
            String str </span>= <span style="color: #0000ff;">new</span><span style="color: #000000;"> String(charArrayWriter.toCharArray());
            </span><span style="color: #0000ff;">byte</span>[] ba =<span style="color: #000000;"> str.getBytes(charset);
            </span><span style="color: #0000ff;">for</span> (<span style="color: #0000ff;">int</span> j = 0; j < ba.length; j++<span style="color: #000000;">) {
                out.append(</span>'%'<span style="color: #000000;">);
                </span><span style="color: #0000ff;">char</span> ch = Character.forDigit((ba[j] >> 4) & 0xF,16<span style="color: #000000;">);
                </span><span style="color: #008000;">//</span><span style="color: #008000;"> converting to use uppercase letter as part of
                </span><span style="color: #008000;">//</span><span style="color: #008000;"> the hex value if ch is a letter.</span>
                <span style="color: #0000ff;">if</span><span style="color: #000000;"> (Character.isLetter(ch)) {
                    ch </span>-=<span style="color: #000000;"> caseDiff;
                }
                out.append(ch);
                ch </span>= Character.forDigit(ba[j] & 0xF,16<span style="color: #000000;">);
                </span><span style="color: #0000ff;">if</span><span style="color: #000000;"> (Character.isLetter(ch)) {
                    ch </span>-=<span style="color: #000000;"> caseDiff;
                }
                out.append(ch);
            }
            charArrayWriter.reset();
            needToChange </span>= <span style="color: #0000ff;">true</span><span style="color: #000000;">;
        }
    }
    </span><span style="color: #0000ff;">return</span> (needToChange?<span style="color: #000000;"> out.toString() : s);
} 
} 
验证下 基本ok                         (编辑:莱芜站长网) 
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! 
                     |