1 package weibo4android
.util
;
2 import java
.io
.UnsupportedEncodingException
;
3 import java
.net
.URLDecoder
;
4 import java
.net
.URLEncoder
;
5 import java
.util
.BitSet
;
10 public class URLEncodeUtils
{
12 static BitSet dontNeedEncoding
;
17 * The list of characters that are not encoded has been determined as
20 * RFC 2396 states: ----- Data characters that are allowed in a URI but
21 * do not have a reserved purpose are called unreserved. These include
22 * upper and lower case letters, decimal digits, and a limited set of
23 * punctuation marks and symbols.
25 * unreserved = alphanum | mark
27 * mark = "-" | "_" | "." | "!" | "~" | "*" | "'" | "(" | ")"
29 * Unreserved characters can be escaped without changing the semantics
30 * of the URI, but this should not be done unless the URI is being used
31 * in a context that does not allow the unescaped character to appear.
34 * It appears that both Netscape and Internet Explorer escape all
35 * special characters from this list with the exception of "-", "_",
36 * ".", "*". While it is not clear why they are escaping the other
37 * characters, perhaps it is safest to assume that there might be
38 * contexts in which the others are unsafe if not escaped. Therefore, we
39 * will use the same list. It is also noteworthy that this is consistent
40 * with O'Reilly's "HTML: The Definitive Guide" (page 164).
42 * As a last note, Intenet Explorer does not encode the "@" character
43 * which is clearly not unreserved according to the RFC. We are being
44 * consistent with the RFC in this matter, as is Netscape.
47 dontNeedEncoding
= new BitSet(256);
49 for (i
= 'a'; i
<= 'z'; i
++) {
50 dontNeedEncoding
.set(i
);
52 for (i
= 'A'; i
<= 'Z'; i
++) {
53 dontNeedEncoding
.set(i
);
55 for (i
= '0'; i
<= '9'; i
++) {
56 dontNeedEncoding
.set(i
);
58 dontNeedEncoding
.set(' '); /*
59 * encoding a space to a + is done in the
62 dontNeedEncoding
.set('-');
63 dontNeedEncoding
.set('_');
64 dontNeedEncoding
.set('.');
65 dontNeedEncoding
.set('*');
67 dontNeedEncoding
.set('+');
68 dontNeedEncoding
.set('%');
78 public static final boolean isURLEncoded(String str
) {
79 if (str
==null||"".equals(str
)) {
82 char[] chars
= str
.toCharArray();
83 boolean containsPercent
= false;
84 for (char c
: chars
) {
85 if (Character
.isWhitespace(c
)) {
88 if (!dontNeedEncoding
.get(c
)) {
92 containsPercent
= true;
101 public static final String
encodeURL(String str
) {
103 return URLEncoder
.encode(str
, "utf-8");
104 } catch (UnsupportedEncodingException e
) {
105 throw new RuntimeException(e
);
108 public static final String
decodeURL(String str
) {
110 return URLDecoder
.decode(str
, "utf-8");
111 } catch (UnsupportedEncodingException e
) {
112 throw new RuntimeException(e
);