You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何移除RestTemplate请求头中的charset=UTF8参数?

移除RestTemplate请求头Content-Type中的charset=UTF8参数

问题场景

使用RestTemplate调用外部API时,框架会自动在Content-Type请求头中追加charset=UTF8参数,示例请求头如下:

POST /v1/documents/validation HTTP/1.1
Accept: application/json
Content-Type: multipart/form-data;charset=UTF8;boundary=gs7Tmph96b0PDkFCrOo9Y7EhtqqV3ok2agluTF

目标API不支持该参数,返回400错误:

"title":"InvalidRequestContent","status":400,"detail":"Request content not conform to API specification: UTF-8;boundary=Kpj8KEbP1NBn3tLmsWgbj8O6LlcGNzyp60ejoi4A"

当前实现代码:

RestTemplate restTemplate = getRestTemplate();

HttpHeaders headers = new HttpHeaders();

headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
headers.add("Content-Type", "multipart/form-data");

headers.add("FSE-JWT-Signature", getHashSignature());
headers.add("Authorization", "Bearer " + getBearerToken());

LinkedMultiValueMap<String, Object> map = new LinkedMultiValueMap<>();

FileSystemResource value = new FileSystemResource(new File(fileName));
map.add("file", value);
map.add("requestBody", requestBody.toString());

HttpEntity<MultiValueMap<String, Object>> request = new HttpEntity<>(map, headers);

解决方案

1. 自定义无字符集的MediaType

不要直接用字符串设置Content-Type,而是创建一个不带字符集的MediaType对象,避免框架自动追加charset参数:

// 替换原有的headers.add("Content-Type", "multipart/form-data");
headers.setContentType(new MediaType("multipart", "form-data"));

2. 修改RestTemplate的消息转换器

如果上述方法不生效,可调整FormHttpMessageConverter的配置,从根源上阻止自动添加字符集:

RestTemplate restTemplate = getRestTemplate();
for (HttpMessageConverter<?> converter : restTemplate.getMessageConverters()) {
    if (converter instanceof FormHttpMessageConverter) {
        FormHttpMessageConverter formConverter = (FormHttpMessageConverter) converter;
        // 清空默认字符集
        formConverter.setCharset(null);
        // 移除所有带字符集的支持媒体类型
        List<MediaType> supportedTypes = new ArrayList<>(formConverter.getSupportedMediaTypes());
        supportedTypes.removeIf(mediaType -> mediaType.getCharset() != null);
        formConverter.setSupportedMediaTypes(supportedTypes);
        break;
    }
}

3. 通过拦截器修改请求头

添加请求拦截器,在请求发送前手动移除Content-Type中的charset部分:

restTemplate.getInterceptors().add((request, body, execution) -> {
    HttpHeaders headers = request.getHeaders();
    if (headers.getContentType() != null) {
        MediaType originalType = headers.getContentType();
        // 创建不带字符集的新MediaType
        MediaType newType = new MediaType(originalType.getType(), originalType.getSubtype());
        headers.setContentType(newType);
    }
    return execution.execute(request, body);
});

内容的提问来源于stack exchange,提问作者nikolas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 19:40:34