1. 程式人生 > 實用技巧 >URLDecoder異常解決方法

URLDecoder異常解決方法

URLDecoder對引數進行解碼時候,程式碼如:

URLDecoder.decode(param,"utf-8");

有時候會出現類似如下的錯誤:

URLDecoder異常Illegal hex characters in escape (%)

這是因為傳參有一些特殊字元,比如%號或者說+號,導致不能解析,報錯

解決方法是:

 1 public static String replacer(StringBuffer outBuffer) {
 2       String data = outBuffer.toString();
 3       try {
 4          data = data.replaceAll("%(?![0-9a-fA-F]{2})", "%25");
5 data = data.replaceAll("\\+", "%2B"); 6 data = URLDecoder.decode(data, "utf-8"); 7 } catch (Exception e) { 8 e.printStackTrace(); 9 } 10 return data; 11 }

URLDecoder原始碼:

 1 public static String decode(String s, String enc)
 2         throws UnsupportedEncodingException{
3 4 boolean needToChange = false; 5 int numChars = s.length(); 6 StringBuffer sb = new StringBuffer(numChars > 500 ? numChars / 2 : numChars); 7 int i = 0; 8 9 if (enc.length() == 0) { 10 throw new UnsupportedEncodingException ("URLDecoder: empty string enc parameter");
11 } 12 13 char c; 14 byte[] bytes = null; 15 while (i < numChars) { 16 c = s.charAt(i); 17 switch (c) { 18 case '+': 19 sb.append(' '); 20 i++; 21 needToChange = true; 22 break; 23 case '%': 24 /* 25 * Starting with this instance of %, process all 26 * consecutive substrings of the form %xy. Each 27 * substring %xy will yield a byte. Convert all 28 * consecutive bytes obtained this way to whatever 29 * character(s) they represent in the provided 30 * encoding. 31 */ 32 33 try { 34 35 // (numChars-i)/3 is an upper bound for the number 36 // of remaining bytes 37 if (bytes == null) 38 bytes = new byte[(numChars-i)/3]; 39 int pos = 0; 40 41 while ( ((i+2) < numChars) && 42 (c=='%')) { 43 int v = Integer.parseInt(s.substring(i+1,i+3),16); 44 if (v < 0) 45 throw new IllegalArgumentException("URLDecoder: Illegal hex characters in escape (%) pattern - negative value"); 46 bytes[pos++] = (byte) v; 47 i+= 3; 48 if (i < numChars) 49 c = s.charAt(i); 50 } 51 52 // A trailing, incomplete byte encoding such as 53 // "%x" will cause an exception to be thrown 54 55 if ((i < numChars) && (c=='%')) 56 throw new IllegalArgumentException( 57 "URLDecoder: Incomplete trailing escape (%) pattern"); 58 59 sb.append(new String(bytes, 0, pos, enc)); 60 } catch (NumberFormatException e) { 61 throw new IllegalArgumentException( 62 "URLDecoder: Illegal hex characters in escape (%) pattern - " 63 + e.getMessage()); 64 } 65 needToChange = true; 66 break; 67 default: 68 sb.append(c); 69 i++; 70 break; 71 } 72 } 73 74 return (needToChange? sb.toString() : s); 75 }