1 17 package org.apache.catalina.util; 18 19 import java.io.ByteArrayOutputStream ; 20 import java.io.IOException ; 21 import java.io.OutputStreamWriter ; 22 import java.util.BitSet ; 23 24 36 public class URLEncoder { 37 protected static final char[] hexadecimal = 38 {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 39 'A', 'B', 'C', 'D', 'E', 'F'}; 40 41 protected BitSet safeCharacters = new BitSet (256); 43 44 public URLEncoder() { 45 for (char i = 'a'; i <= 'z'; i++) { 46 addSafeCharacter(i); 47 } 48 for (char i = 'A'; i <= 'Z'; i++) { 49 addSafeCharacter(i); 50 } 51 for (char i = '0'; i <= '9'; i++) { 52 addSafeCharacter(i); 53 } 54 } 55 56 public void addSafeCharacter( char c ) { 57 safeCharacters.set( c ); 58 } 59 60 public String encode( String path ) { 61 int maxBytesPerChar = 10; 62 int caseDiff = ('a' - 'A'); 63 StringBuffer rewrittenPath = new StringBuffer (path.length()); 64 ByteArrayOutputStream buf = new ByteArrayOutputStream (maxBytesPerChar); 65 OutputStreamWriter writer = null; 66 try { 67 writer = new OutputStreamWriter (buf, "UTF8"); 68 } catch (Exception e) { 69 e.printStackTrace(); 70 writer = new OutputStreamWriter (buf); 71 } 72 73 for (int i = 0; i < path.length(); i++) { 74 int c = (int) path.charAt(i); 75 if (safeCharacters.get(c)) { 76 rewrittenPath.append((char)c); 77 } else { 78 try { 80 writer.write((char)c); 81 writer.flush(); 82 } catch(IOException e) { 83 buf.reset(); 84 continue; 85 } 86 byte[] ba = buf.toByteArray(); 87 for (int j = 0; j < ba.length; j++) { 88 byte toEncode = ba[j]; 90 rewrittenPath.append('%'); 91 int low = (int) (toEncode & 0x0f); 92 int high = (int) ((toEncode & 0xf0) >> 4); 93 rewrittenPath.append(hexadecimal[high]); 94 rewrittenPath.append(hexadecimal[low]); 95 } 96 buf.reset(); 97 } 98 } 99 return rewrittenPath.toString(); 100 } 101 } 102 | Popular Tags |