javaencoder编码_de的默认编码问题今天要实现的⼀个功能是在页⾯上上传⽂件到后台,⽂件是txt格式,每⾏是⼀个url,后台读取后,对路径中的中⽂进⾏url编码
如下是我的代码:
Pattern chinesePattern = Patternpile("[\\u4e00-\\u9fa5]+");
MultipartFile file = null;
try {
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (isMultipart) {
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
file = File("file");
String line = null;
SeturlOrNameSet = new HashSet<>();
BufferedReader reader = new BufferedReader(new InputStream(), "GB18030"));//这⾥其实默认也是⽤GB18030编码读⼊
while ((line = adLine()) != null) {
if(StringUtils.isNotBlank(line)) {
line = im();
Matcher matcher = chinesePattern.matcher(line);
while (matcher.find()) {
line = up(), up());
}
urlOrNameSet.add(line);
}
}
}
} catch (Exception e) {
<("batch import fail: {}", e);
}url编码和utf8区别
但是发现⼀个诡异的问题,编码后的路径,是错误的,根本访问不了,见⿁,于是我做了⼀个单元测试:
@Test
public void testUrl() throws Exception {
String url = "baike.baidu/item/乒乓球台/2565939";
Pattern chinesePattern = Patternpile("[\\u4e00-\\u9fa5]+");
Matcher matcher = chinesePattern.matcher(url);
while (matcher.find()) {
url = up(), up()));
}
System.out.println(url);
}
可以看到代码和上⾯是⼀模⼀样的,但是这种⽅式编码后的路径就可以正常访问,⽽且的确可以看到,上⾯编码后的路径和这⾥单元测试编码后的路径不⼀样
真是见⿁,代码明明⼀样,为什么结果不⼀样,⾸先想到的应该是编码问题,可是这两个地⽅的url都是UTF-8的,所以url的编码是⼀致的,问题不在url这⾥
最后我想到是否可能是在de的过程中出了问题,于是我先进去源码可以看到:
@Deprecated
public static String encode(String s) {
String str = null;
try {
str = encode(s, dfltEncName);
} catch (UnsupportedEncodingException e) {
// The system should always have the platform default
}
return str;
}
可以看到这是个过时的⽅法,当然这不是重点,重点是这⾥有⼀个默认编码dfltEncName,于是我debug看了下,单元测试的地⽅,这⾥的默认编码是UTF-8,但是我的项⽬⾥⾯这⾥居然是GBK,于是我改成了如下代码:
line = up(), up(), "UTF-8"));
问题终于得到了解决

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。