环境
java:1.7
场景
今天在测试接口时,发现报了这个错误:
我接口传的参数:
event_name=龙虎榜&estimate_name=日涨幅偏离值达到7%
详细错误如下:
java.lang.IllegalArgumentException: URLDecoder: Incomplete trailing escape (%) pattern
at java.net.URLDecoder.decode(URLDecoder.java:187)
at ggservice.v1.event.service.InfoEventService.getInfoEventList(InfoEventService.java:215)
at ggservice.v1.event.action.GetInfoEventListAction.fly(GetInfoEventListAction.java:46)
at ggservice.v1.event.action.GetInfoEventListAction.fly(GetInfoEventListAction.java:1)
at ggframework.core.api.FlyAction.doExecute(FlyAction.java:76)
at ggframework.core.api.ApiBaseAction.execute(ApiBaseAction.java:26)
at ggframework.core.api.ApiBaseAction.execute(ApiBaseAction.java:15)
at ggframework.core.api.extension.ExtensionInvoker.run(ExtensionInvoker.java:61)
at ggframework.core.api.DataServiceDispatcher.dispatcher(DataServiceDispatcher.java:73)
at controllers.ggservice.DataHandler.execute(DataHandler.java:15)
at play.mvc.ActionInvoker.invokeWithContinuation(ActionInvoker.java:557)
at play.mvc.ActionInvoker.invoke(ActionInvoker.java:508)
at play.mvc.ActionInvoker.invokeControllerMethod(ActionInvoker.java:484)
at play.mvc.ActionInvoker.invokeControllerMethod(ActionInvoker.java:479)
at play.mvc.ActionInvoker.invoke(ActionInvoker.java:161)
at Invocation.HTTP Request(Play!)
我的主要代码如下:
infoQuery.append("title", java.net.URLDecoder.decode(estimateName, "UTF-8"));
出现这个错误的主要原因是,在接收字段estimate_name
的值时,浏览器传过来的是这样的:
%E6%97%A5%E6%B6%A8%E5%B9%85%E5%81%8F%E7%A6%BB%E5%80%BC%E8%BE%BE%E5%88%B07%
我们知道中文的话,浏览器肯定会转码,但是转码后的格式一般都是%两个字符
,也就是百分号后面,接英文字母或者数字!
但是假设参数中原本就有百分号%
的话,这时浏览器不会处理,接着再使用decode
进行解码时,会出错,因为java程序
认为后面应该还有两个字符才对,结果没有。。。
解决办法
只需要把单独出现的%
替换成转码后的字符就行了,也就是%25
。
这里强调下,网上很多的改法如下:
estimateName = estimateName.replaceAll("%", "%25");
上面这种写法是错误的,因为其把正确的都替换掉了。
这里我们需要明白,要替换掉的是单独出现的百分号,而不是全部的百分号
正确改法
estimateName = estimateName.replaceAll("%(?![0-9a-fA-F]{2})", "%25");
上的字符串就会解码成如下格式(重点看最后):
%E6%97%A5%E6%B6%A8%E5%B9%85%E5%81%8F%E7%A6%BB%E5%80%BC%E8%BE%BE%E5%88%B07%25
讲解下%(?![0-9a-fA-F]{2})
:
这是个正则表达式,含义是:不匹配%后面两位为
数字或字母(包括大小写)的字符;这样就把正确的排除掉了,剩下的就是需要匹配替换的。
最后附上url
编码地址:
HTML URL 编码
Java正确URL解码方式:URLDecoder.decode
总结
网上的真正有价值的资料,很少,很多都需要我们自己去验证!