原文:Java只给汉字转URLEncoder
转码起因:线上图片显示异常,因为IOS无法显示带中文的图片链接,在之前的文章中介绍了通过转码进行正常显示,后面发现原来的那个转码有问题,不单单是对中文进行转码,对“%E4%BC%81%E4%B8%9A%E5%BE%AE%E4%BF%A1%E6%88%AA%E5%9B%BE”也进行了二次转码,导致链接失效。
@Testpublic void test() throws UnsupportedEncodingException {
Pattern p = Pattern.compile("[\u4e00-\u9fa5]+");String a = "https://kos-oss-test.oss-cn-hangzhou.aliyuncs.com/images/企业微信截图_20211229e0a4899a905a4b6d8f0f2d88f8288cd0%E4%BC%81%E4%B8%9A%E5%BE%AE%E4%BF%A1%E6%88%AA%E5%9B%BE_16407530994802.png";Matcher m = p.matcher(a);StringBuffer b = new StringBuffer();while (m.find()) {
m.appendReplacement(b, URLEncoder.encode(m.group(0), "utf-8"));}m.appendTail(b);System.out.println(b.toString());String encode = URLEncoder.encode("企业微信截图", "utf-8");System.out.println(encode);}
结果:
https://kos-oss-test.oss-cn-hangzhou.aliyuncs.com/images/%E4%BC%81%E4%B8%9A%E5%BE%AE%E4%BF%A1%E6%88%AA%E5%9B%BE_20211229e0a4899a905a4b6d8f0f2d88f8288cd0%E4%BC%81%E4%B8%9A%E5%BE%AE%E4%BF%A1%E6%88%AA%E5%9B%BE_16407530994802.png
%E4%BC%81%E4%B8%9A%E5%BE%AE%E4%BF%A1%E6%88%AA%E5%9B%BE
通过对比,确实只转码了中文部分