【发布时间】:2018-02-28 04:39:05
【问题描述】:
我有一个 Spring Boot REST 应用程序 (1.5.6.RELEASE)。我想要 gzip 压缩传入和传出。根据这个文档https://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html我已经设置了
server.compression.enabled=true
server.compression.mime-types=...
但这似乎只适用于来自我的服务的 gzipping 响应(这就是文档实际上所说的“# If response compression is enabled.”)。
我的问题是传入的 gzipped 请求没有被解压缩,导致 JSON 解析错误。
有人知道如何在我的 Spring Boot 应用中开启请求解压功能吗?
编辑一个例子:
POM sn-p:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.6.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
控制器代码:
@RestController
public class Controller {
@RequestMapping(value = "/", method = RequestMethod.POST, consumes = "application/json")
public String post(@RequestBody Map<String, String> request) {
return request.get("key");
}
}
使用 curl 测试:
$ echo '{ "key":"hello" }' > body
$ curl -X POST -H "Content-Type: application/json" --data-binary @body http://localhost:8080 # prints 'hello'
$ echo '{ "key":"hello" }' | gzip > body.gz
$ curl -X POST -H "Content-Type: application/json" -H "Content-Encoding: gzip" --data-binary @body.gz http://localhost:8080 # fails
gzipped 调用失败并显示消息:
{"timestamp":1505843443456,"status":400,"error":"Bad Request","exception":"org.springframework.http.converter.HttpMessageNotReadableException","message":"JSON parse error: Illegal character ((CTRL-CHAR, code 31)): only regular white space (\\r, \\n, \\t) is allowed between tokens; nested exception is com.fasterxml.jackson.core.JsonParseException: Illegal character ((CTRL-CHAR, code 31)): only regular white space (\\r, \\n, \\t) is allowed between tokens\n at [Source: java.io.PushbackInputStream@50ebec25; line: 1, column: 2]","path":"/"}
【问题讨论】:
-
如何发出压缩请求?
-
@diginoise 我无法控制客户端
-
给我们看一些代码!你的控制器是什么样的?客户端发送的是什么(HTTP 标头和正文),您遇到了什么错误,等等
-
@Brian Clozel,完成
标签: java spring rest spring-boot