String url = "/spa/meeting/static4mobile/index.html#/calendar/detail?type=create&caller=128&contacter=135&address=abc&name=nnnn";
//url编码--java
url = URLEncoder.encode(url, "utf-8");
//输出:%2fspa%2fmeeting%2fstatic4mobile%2findex.html%23%2fcalendar%2fdetail%3ftype%3dcreate%26caller%3d128%26contacter%3d135%26address%3dabc%26name%3dnnnn
//url解码--java
url = URLDecoder.decode(easstAppSsoCode, "utf-8");
//输出:/spa/meeting/static4mobile/index.html#/calendar/detail?type=create&caller=128&contacter=135&address=abc&name=nnnn
encode存在的问题:
java服务端用URLEncoder.encode方法编码会把空格变成加号(+)。导致在前台页面显示的时候会多出加号。
例如:
上传的文件名为 “新建 文本文档.txt”文件名中间有空格 ,从后台返回值解码后却变成了“新建+文本文档.txt”
例如:
servlet后端跳转静态资源html页面。url拼接参数值“2019-11-20 17:03:09”,
使用URLEncoder.encode("2019-11-20 17:03:09", "utf-8")编码后变成“2019-11-20+17%3A03%3A09”
导致页面上填入表单的值是“2019-11-20+17:03:09”
解决方法:
encode编码后,先把变量中的加号(+)全部替换为“%20”。str=str.replaceAll("\\+","%20");
再把替换后的值拼接到url中,最后将这个url返回给前端页面,让浏览器访问。
解决示例:
String paramValue = "2019-11-20 17:03:09";
String replaceValue = URLEncoder.encode(paramValue,"utf-8").replaceAll("\\+","%20");//2019-11-20%2017%3A03%3A09
decode存在的问题:
java.net的url编码方法在对一些特殊符号编码时有个bug,如:+号decode后会变成空格。
问题现象:
String testStr = URLDecoder.decode("1+2=3", "utf-8");
System.out.println("testStr="+testStr);//1 2=3
解决办法:
需要把+号替换成%2b,str=str.replaceAll("\\+", "%2b");
解决示例:
String testStr = URLDecoder.decode("1+2=3".replaceAll("\\+", "%2b"), "utf-8");
System.out.println("testStr="+testStr);//1+2=3
总结:
URLEncoder.encode编码时不需要+,需要空格。编码后str.replaceAll("\\+","%20")
URLDecoder.decode解码是需要+,不需要空格。解码前str.replaceAll("\\+","%2b")