1 19 20 package com.maverick.http; 21 22 import java.io.UnsupportedEncodingException ; 23 24 28 public class HttpUtil { 29 30 private static final String ACCEPTABLE = "ABCDEFGHIJLKMNOPQRSTUVWXYZ" + "abcdefghijklmnopqrstuvwxyz" + "0123456789" + "_-!.~'()*" + ",;:$+=" + "?/@"; 38 45 public static String encodePath(String path, boolean encodeSlash, String charset) { 46 47 StringBuffer buffer = new StringBuffer (); 48 byte encoded[]; 49 try { 50 if (charset == null) 51 encoded = path.getBytes(); 52 else 53 encoded = path.getBytes(charset); 54 for (int x = 0; x < encoded.length; x++) { 55 if (((int) encoded[x] == '%' && encodeSlash) || ACCEPTABLE.indexOf((int) encoded[x]) < 0) { 56 buffer.append('%'); 57 buffer.append(toHexString(encoded[x])); 58 continue; 59 } 60 buffer.append((char) encoded[x]); 61 } 62 } catch (UnsupportedEncodingException e) { 63 e.printStackTrace(); 64 return path; 65 } 66 67 return buffer.toString(); 68 } 69 70 78 public static String toHexString(byte buffer[]) { 79 char output[] = new char[buffer.length * 2]; 80 int position = 0; 81 for (int x = 0; x < buffer.length; x++) { 82 output[position++] = toHexDigit(buffer[x] >> 4); 83 output[position++] = toHexDigit(buffer[x]); 84 } 85 return new String (output); 86 } 87 88 96 public static String toHexString(byte number) { 97 char output[] = new char[2]; 98 output[0] = toHexDigit((int) (number >> 4)); 99 output[1] = toHexDigit((int) (number)); 100 return new String (output); 101 } 102 103 112 private static char toHexDigit(int number) { 113 switch (number & 0x0F) { 114 case 0x00: 115 return '0'; 116 case 0x01: 117 return '1'; 118 case 0x02: 119 return '2'; 120 case 0x03: 121 return '3'; 122 case 0x04: 123 return '4'; 124 case 0x05: 125 return '5'; 126 case 0x06: 127 return '6'; 128 case 0x07: 129 return '7'; 130 case 0x08: 131 return '8'; 132 case 0x09: 133 return '9'; 134 case 0x0A: 135 return 'A'; 136 case 0x0B: 137 return 'B'; 138 case 0x0C: 139 return 'C'; 140 case 0x0D: 141 return 'D'; 142 case 0x0E: 143 return 'E'; 144 case 0x0F: 145 return 'F'; 146 } 147 String message = "Invalid HEX digit " + Integer.toHexString(number); throw new IllegalArgumentException (message); 149 } 150 151 } 152 | Popular Tags |