1 25 26 package org.snipsnap.util; 27 28 import java.io.UnsupportedEncodingException ; 29 import java.util.BitSet ; 30 31 39 public class URLEncoderDecoder { 40 41 private static BitSet dontNeedEncoding; 42 43 static { 44 dontNeedEncoding = new BitSet (256); 45 int i; 46 for (i = 'a'; i <= 'z'; i++) { 47 dontNeedEncoding.set(i); 48 } 49 for (i = 'A'; i <= 'Z'; i++) { 50 dontNeedEncoding.set(i); 51 } 52 for (i = '0'; i <= '9'; i++) { 53 dontNeedEncoding.set(i); 54 } 55 dontNeedEncoding.set(' '); 57 dontNeedEncoding.set('-'); 58 dontNeedEncoding.set('_'); 59 dontNeedEncoding.set('.'); 60 dontNeedEncoding.set('*'); 61 dontNeedEncoding.set('/'); 62 dontNeedEncoding.set(':'); 63 } 64 65 66 70 public static String encode(String s, String enc) throws UnsupportedEncodingException { 71 byte[] buf = s.getBytes(enc); 72 StringBuffer result = new StringBuffer (); 73 for (int i = 0; i < buf.length; i++) { 74 int c = (int) buf[i]; 75 if (dontNeedEncoding.get(c & 0xFF)) { 76 result.append((char) c); 77 } else { 78 result.append('%').append(Integer.toHexString(c & 0xFF).toUpperCase()); 79 } 80 } 81 return result.toString(); 82 } 83 84 90 public static String decode(String s, String enc) throws UnsupportedEncodingException { 91 byte[] buf = new byte[s.length()]; 92 int length = 0; 93 for (int i = 0; i < s.length(); i++) { 94 char c = s.charAt(i); 95 if (c == '%') { 96 buf[length++] = (byte) Integer.parseInt(s.substring(i + 1, i + 3), 16); 97 i += 2; 98 } else { 99 buf[length++] = (byte) c; 100 } 101 } 102 return new String (buf, 0, length, enc); 103 } 104 } 105 | Popular Tags |