关于java:getBytes引发的编码错误

在应用restTemplate作申请的时候,外部退出了一个interceptor来解决应答体的解码工作,返回了new ByteArrayInputStream(repsonse.getBytes())把json解析为对象,在ide里代码运行时没有什么问题,后续打包后用bat脚本在win10上运行,却报JSON parse error:Invalid UTF-8 start byte谬误。

猜想是windows上运行未采纳utf-8,查看getBytes()源码,无参结构时会应用defaultCharset()去优先查找应用文件的编码方式,未找到才应用utf-8编码。所以在应用bat脚本运行时getBytes()没有采纳utf-8编码。

 public static Charset defaultCharset() {
        if (defaultCharset == null) {
            synchronized (Charset.class) {
                String csn = AccessController.doPrivileged(
                    new GetPropertyAction("file.encoding"));
                Charset cs = lookup(csn);
                if (cs != null)
                    defaultCharset = cs;
                else
                    defaultCharset = forName("UTF-8");
            }
        }
        return defaultCharset;
    }

应用getBytes(StandardCharsets.UTF-8)解决问题。

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理