Java URLEncoder 兼容 js encodeURIComponent
js的encodeURIComponent与java的URLEncoder.encode编码后不同的字符有如下六个:
原本 | js | java |
---|---|---|
空格 | %20 | + |
) | ) | %29 |
( | ( | %28 |
' | ' | %27 |
! | ! | %21 |
~ | ~ | %7E |
Java 处理类
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
/**
* @author linyufeng.
* @date 2021/4/19 14:32
**/
public class JsToolUtil {
/**
* 处理编码格式为js兼容模式
* @param str
* @return
* @throws UnsupportedEncodingException
*/
public static String encodeURIComponent(String str) throws UnsupportedEncodingException {
return URLEncoder.encode(str, "UTF-8")
.replaceAll("\\+", "%20")
.replaceAll("%28", "(")
.replaceAll("%29", ")")
.replaceAll("%27", "'")
.replaceAll("%21", "!")
.replaceAll("%7E", "~");
}
public static void main(String[] args) throws UnsupportedEncodingException {
String s = "(A=\"范广洲\") AND (O='成都信息工程大学')";
System.out.println(URLEncoder.encode(s, "UTF-8"));
System.out.println(encodeURIComponent(s));
}
}
结果:
%28A%3D%22%E8%8C%83%E5%B9%BF%E6%B4%B2%22%29+AND+%28O%3D%27%E6%88%90%E9%83%BD%E4%BF%A1%E6%81%AF%E5%B7%A5%E7%A8%8B%E5%A4%A7%E5%AD%A6%27%29
(A%3D%22%E8%8C%83%E5%B9%BF%E6%B4%B2%22)%20AND%20(O%3D'%E6%88%90%E9%83%BD%E4%BF%A1%E6%81%AF%E5%B7%A5%E7%A8%8B%E5%A4%A7%E5%AD%A6')
参考: