首页 > 其他分享 >获取网络图片报错,url编码问题(url中含有中文)

获取网络图片报错,url编码问题(url中含有中文)

时间:2023-01-09 14:11:27浏览次数:60  
标签:tmp 编码 中文 String url matcher 报错

报错信息:java.io.IOException: Server returned HTTP response code: 400 for URL: http://

 

错误:使用poi导出会议记录word,其中包含文字和图片,导出时图片无法显示。

原因:debug发现在通过url获取网络流时报错。在百度后得知是url中包含中文导致的。

一般来说,URL只能使用英文字母、阿拉伯数字和某些标点符号,不能使用其他文字和符号。

这是网络标准RFC 1738的硬性规定:  
解决方案:对url中非法内容进行编码
public static void main(String[] args) throws UnsupportedEncodingException {
        String url="https://img-s-msn-com.akamaized.net/tenant/amp/entityid/AA165W2U非法中文.img";
        Matcher matcher =Pattern.compile("[\\u4e00-\\u9fa5]|[\\u3002\\uff1b\\uff0c\\uff1a\\u201c\\u201d\\uff08\\uff09\\u3001\\uff1f\\u300a\\u300b\\u3010\\u3011]").matcher(url);
        while (matcher.find()) {
            String tmp = matcher.group();
            try {
                url = url.replaceAll(tmp, java.net.URLEncoder.encode(tmp, "utf-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }

        System.out.println(url);
    }
[\\u4e00-\\u9fa5] 代表匹配所有中文。 其他需要匹配的符号可以在自己加上。

 

标签:tmp,编码,中文,String,url,matcher,报错
From: https://www.cnblogs.com/ELECFENG/p/17036891.html

相关文章