首页 > 解决方案 > 为什么是IDEA编译的,HTTP POST请求内容会自动转成GBK编码

问题描述

我正在写一个 IDEA 插件

使用 Spring 库发送 POST 请求时,中文会自动转换为 GBK 编码。

这是我抓到http包时发现的问题。

通过各种排查,发现在Debug模式下,单独运行main函数,POST的内容确实是UTF-8编码。但是编译后POST的内容会自动转换成GBK编码。

这是我的代码。

public static void main(String[] args) {
    String content = "nLog(1)";
    String ip = "172.16.10.23";
    String path = "/test";
    String fileName = "中文123.lua";
    String url = "http://" + ip + ":50005/upload";
    RestTemplate restTemplate = new RestTemplate();
    restTemplate.getMessageConverters()
            .add(0, new StringHttpMessageConverter(StandardCharsets.UTF_8));
    HttpHeaders headers = new HttpHeaders();
    headers.add("root", "lua");
    headers.add("auth", "");
    headers.add("Host", ip);
    headers.add("path", path);
    headers.add("filename", fileName);
    headers.add("Connection", "close");
    headers.add("Content-Type", "touchsprite/uploadfile");
    headers.add("Content-Length", String.valueOf(content.length()));
    System.out.println(headers);
    HttpEntity<String> entity = null;
    entity = new HttpEntity<>(content, headers);
    restTemplate.postForObject(url, entity, String.class);
}

标签: javaintellij-idea

解决方案


推荐阅读