报错如下
java.lang.IllegalArgumentException: URLDecoder: Illegal hex characters in escape (%) pattern - For input string: “����”
如果url中有%或者+会报上面的错误
这里以%为例:
浏览器URL只能是英文、阿拉伯数字和标点符号,中文的话需要编码解码,浏览器遇到中文会自动的编码为%B2这样的%加16进制的,可是%不会处理。
就像”你好啊%“,最终变成了”%B2%E2%CA%D4%B1%A8%B4%ED%“
%在被编码的时候变成了%25,我们传进来的url本来包括%的话,浏览器不会进行处理,还是%,但是在解码的时候,程序认为%后面还应该有25,可是的的确确没有这个25,解码的程序不认识了,不知道怎么解码了,就抛出了异常java.lang.IllegalArgumentException
原来的解码前加两行代码
val = val.replaceAll("%(?![0-9a-fA-F]{2})", "%25");
val = val.replaceAll("\\+", "%2B");
val = URLDecoder.decode(val, "utf-8");
package com.leesin;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
public class DecodeTest {
public static void main(String[] args) throws UnsupportedEncodingException {
String testString = "测试没有特殊字符的解码";
String encode = URLEncoder.encode(testString, "gbk");
String decode = URLDecoder.decode(encode, "gbk");
System.out.println("没有特殊字符解码的--" + encode);
System.out.println("没有特殊字符解码的--" + decode);
String testString1 = "%测试有特殊字符的解码";
String encode1 = URLEncoder.encode(testString1, "gbk");
String decode1 = URLDecoder.decode(encode1, "gbk");
System.out.println("有特殊字符解码的--" + encode1);
System.out.println("有特殊字符解码的--" + decode1);
String testString2 = "测试报错%";
// String encode2 = URLEncoder.encode(testString2, "gbk");
String encode2 = "%B2%E2%CA%D4%B1%A8%B4%ED%";
String decode2 = URLDecoder.decode(encode2, "gbk");
System.out.println("有特殊字符解码的--" + encode2);
System.out.println("有特殊字符解码的--" + decode2);
}
}
java转义问题【java.lang.IllegalArgumentException: URLDecoder: Incomplete trailing escape (%) pattern】