Spring Boot v2.4.2如何移除响应头Content-Type中的charset=UTF-8
解决方案
方法1:调整接口返回类型与MediaType设置方式
- 首先将方法返回的
ResponseEntity<?>改为明确的ResponseEntity<byte[]>,避免Spring误将二进制响应用字符类型转换器处理 - 不要直接用
header方法设置Content-Type,改用contentType()方法传入无字符集的MediaType.APPLICATION_PDF实例,该MediaType默认不带charset属性,Spring处理时不会额外追加字符集
修改后的代码示例:
@GetMapping(value = "/view/{clientId}/{documentId}", produces = MediaType.APPLICATION_PDF_VALUE) public ResponseEntity<byte[]> downloadDocument(@PathVariable String clientId, @PathVariable String documentId) { // 原有业务逻辑省略 return ResponseEntity.ok() .contentLength(/* 你的文件长度参数 */) .contentType(MediaType.APPLICATION_PDF) .header(HttpHeaders.CONTENT_DISPOSITION,"inline; filename=\"download.pdf\"") .body(downloadInputStream.toByteArray()); }
方法2:调整HTTP消息转换器顺序
Spring默认会优先用字符相关的消息转换器处理响应,可能给非文本类型也追加字符集,你可以配置将处理二进制流的ByteArrayHttpMessageConverter放到转换器列表最前面,在配置类中添加如下配置:
@Configuration public class WebConfig implements WebMvcConfigurer { @Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { converters.add(0, new ByteArrayHttpMessageConverter()); } }
方法3:修正编码配置项
如果你使用的是Spring Boot 2.0+版本,原来的spring.http.encoding配置已废弃,改为server.servlet.encoding前缀,需要在application.properties中添加以下配置:
server.servlet.encoding.force=false server.servlet.encoding.force-response=false
以上三种方法按顺序尝试即可,大部分场景下第一种方法就能解决问题。
内容的提问来源于stack exchange,提问作者Roul
相关产品推荐
相关产品推荐

