springBoot资源下载pdf中。返回400问题。
因为在拼接的url中是存在中文的。但是多个接口都没有报错。下载pdf的时候报错了。没有考虑中文的问题。尝试了
URLEncoder.encode
整段转成编码发现在浏览器中是无法正常打开的。但是只要把URL中的字转化成编码就可以正常打开了
http://127.0.0.1:8080/profile/avatar/2024/05/04/加油-张三-发票-0120-238_20240504100948A001.pdf
这里中间的汉字影响了下载。
/**
* 中文转化成 Encoder 编码
*/
private String chineseReplace(String urlString ){
// 使用正则表达式匹配中文字符
Pattern pattern = Pattern.compile("[\\u4e00-\\u9fa5]"); // 中文字符范围
Matcher matcher = pattern.matcher(urlString);
// 逐个字符替换为 URL 编码格式
StringBuffer sb = new StringBuffer();
while (matcher.find()) {
String chineseChar = matcher.group(); // 匹配到的中文字符
try {
String encodedChar = URLEncoder.encode(chineseChar, "UTF-8"); // 中文字符转换为 URL 编码格式
matcher.appendReplacement(sb, encodedChar); // 替换为 URL 编码格式
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
matcher.appendTail(sb);
// 输出替换后的 URL 字符串
String encodedUrlString = sb.toString();
return encodedUrlString;
}
使用了正则匹配。去匹配里面中间的汉字。在把中间的汉字单独转化成编码就能正常下载了。
http://127.0.0.1:8080/profile/avatar/2024/05/04/%E5%8A%A0%E6%B2%B9-%E8%82%96%E4%B8%9C%E5%B1%B1-0120-238_20240504100948A001.pdf
转化后的数据之后就能在浏览器正常打开。并且springBoot资源也能正常下载了。