问题描述
最近在优化钉钉告警消息的功能,需要将url由后端返回,markdown文本显示为链接的形式,当url参数包含中文,或者参数值包含中文或空格时,需要对参数或参数值进行urlencode。
但是当包含空格时,发现单纯使用URLEncoder.encode(url, “UTF-8”)是不够的。
其实际表现与js中的encodeURLComponent不同。对于空格encode后为”+”,而js中为 %20
Java中实现js中的encodeURLComponent
使用 utf-8 encode后,需要对特定字符做替换
https://blog.csdn.net/wangweiren_get/article/details/82585629
public static String encodeURIComponent(String s) {String result = null;try {result = URLEncoder.encode(s, "UTF-8").replaceAll("\\+", "%20").replaceAll("\\%21", "!").replaceAll("\\%27", "'").replaceAll("\\%28", "(").replaceAll("\\%29", ")").replaceAll("\\%7E", "~");}// This exception should never occur.catch (UnsupportedEncodingException e) {result = s;}return result;}
