如何在 Spring boot(v2.4.2) 中从 Content-Type 响应 header 中删除 charset=UTF-8

How to remove charset=UTF-8 from Content-Type response header in Spring boot(v2.4.2)

我正在尝试从 s3 下载 pdf 文件,然后 return 作为字节数组的响应。除了“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"
  }
}

charset=UTF-8 通常用于纯文本简单 pdf 文件,因为服务器只是假设没有“内容传输编码”。 inline就是加载使用,附件弹出对话框。 link 中的第 2 页和第 3 页显示了如何正确设置 servlet 下载。 http://www.windsolarhybridaustralia.x10.mx/Ramfile-html_B_.pdf

您尝试过以下属性吗?

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

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

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