// 转码
String str = URLEncoder.encode("中国", "utf-8");
System.out.println(str); // 打印: %E4%B8%AD%E5%9B%BD
// 解码
String str1 = URLDecoder.decode(str, "UTF-8");
System.out.println(str1); // 打印:中国
---------------------------------------------------------
有时候前端页面提交中文字符串时,java 后端获得的是乱码,这时需要在页面 js 里用 encodeURIComponent 对中文参数进行编码,之后 java 后台才能获得提交到后台的中文参数,或者在 java 后端再用 URLDecoder.decode(str, "UTF-8") 对获得的参数解码获得提交的中文参数。
js 转码:
用 encodeURIComponent() 对链接 '?' 后面的参数进行编码,它会对一些特殊字符( ; / ? : @ & = + $ , #等 )进行编码
encodeURIComponent(",/?:@&=+$#")
打印结果:%2C%2F%3F%3A%40%26%3D%2B%24%23
encodeURIComponent('a=12&b=12/12')
打印结果:a%3D12%26b%3D12%2F12
js 解码:
很多网站的 cookie 在进行编码的时候,是 encodeURIComponent 格式的,所以应该使用 decodeURIComponent( str ) 进行解码。