首页 > 解决方案 > 如何在 Spring boot(v2.4.2) 中从 Content-Type 响应标头中删除 charset=UTF-8

问题描述

我正在尝试从 s3 下载 pdf 文件,然后将响应作为字节数组返回。除了“Content-Type”之外,一切正常,在 Content-Type 中添加了 charset=UTF-8。

我在 application.properties 中包含了“spring.http.encoding.force=false”。以下是我的代码片段:

@GetMapping(value = "/view/{clientId}/{documentId}", produces = { "application/pdf" })
public ResponseEntity<?> downloadDocument(@PathVariable String clientId,
                                              @PathVariable String documentId) {

....
return ResponseEntity.ok()
                    .contentLength(...)
                    .header(HttpHeaders.CONTENT_TYPE, "application/pdf")
                    .header(HttpHeaders.CONTENT_DISPOSITION,"inline; filename=\"download.pdf\"")
                    .body(downloadInputStream.toByteArray());
}

在响应日志中,我得到以下信息:

{
  "type": "response",
  "correlation": "e297f48c4475d510",
  "direction": "EGRESS",
  "duration": 5536,
  "protocol": "HTTP/1.1",
  "status": 200,
  "headers": {
    "Keep-Alive": "timeout=360",
    "x-request-id": "e297f48c4475d510",
    "Content-Disposition": "inline; filename=\"download.pdf\"",
    "Connection": "keep-alive",
    "Content-Length": "864038",
    "Date": "Thu, 01 Jul 2021 09:53:08 GMT",
    "Content-Type": "application/pdf;charset=UTF-8"
  }
}

标签: javaspring-bootmime-types

解决方案


您是否尝试过以下属性?

server.servlet.encoding.force=false
server.servlet.encoding.forceResponse=false

但是,这两个属性都应默认为 false,因此除非明确设置为 true,否则它不会为您设置编码。

另一种可能性是HttpServletResponse.setCharacterEncoding()在您的代码或库中的某处调用。您可以尝试调试该方法以查看是否有任何类正在调用它。


推荐阅读