java转义问题【java.lang.IllegalArgumentException: URLDecoder: Incomplete trailing escape (%) pattern】

环境

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

总结

网上的真正有价值的资料,很少,很多都需要我们自己去验证!

  • 10
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 9
    评论
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

山鬼谣me

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值