java - 如何将 Spring Webclient 的内容类型设置为“application/json-patch+json”
问题描述
我正在尝试向另一个接受内容类型“application/json-patch+json”的 API 发出补丁休息请求。我正在使用 Spring 的 webclient,但我无法让它工作。我不断收到“415 不支持的媒体类型”
我已经尝试过以下方法;
WebClient webClient = WebClient.create(baseUrl);
Mono<ClientResponse> response = webClient.patch()
.uri(updateVmfExecutionApi, uuid)
.header("Content-Type", "application/json-patch+json")
.body(BodyInserters.fromFormData("lastKnownState", state))
.exchange();
我也试过:
WebClient webClient = WebClient.create(baseUrl);
Mono<ClientResponse> response = webClient.patch()
.uri(updateVmfExecutionApi, uuid)
.contentType(MediaType.valueOf("application/json-patch+json"))
.body(BodyInserters.fromFormData("lastKnownState", state))
.exchange();
对于这两种情况,我都会看到以下错误;
{"timestamp":"2020-09-17T20:50:40.818+0000","status":415,"error":"Unsupported Media Type","exception":"org.springframework.web.HttpMediaTypeNotSupportedException","message":"Unsupported Media Type","trace":"org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported\n\tat org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping.handleNoMatch(RequestMappingInfoHandlerMapping.java:215)\n\tat org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.lookupHandlerMethod(AbstractHandlerMethodMapping.java:421)\n\tat org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.getHandlerInternal(AbstractHandlerMethodMapping.java:367)\n\tat org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping.getHandlerInternal(RequestMappingHandlerMapping.java:449)
似乎它更改为 'application/x-www-form-urlencoded;charset=UTF-8' 甚至可以将 webclient 用于这种内容类型吗?
解决方案
如果您查看异常,您会看到它说
Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported
它将其更改为formdata。那是因为您在正文中实际发送的内容具有优先权。在您的代码中,您要说明以下内容以发送正文。
.body(BodyInserters.fromFormData("lastKnownState", state))
这表明您正在发送表单数据,这是一种发送数据的键值方式,然后webclient会自动为您设置内容类型标头为x-www-form-urlencoded
.
如果您想要一个 json 内容类型标头,则需要发送 json 数据。发送 json 是 webclient 的默认方式,因此您需要做的就是正确传递正文。有几种以标准方式传递身体的方法。
通过传递生产者(可以是 aMono
或 a Flux
)。
.body(Mono.just(data))
使用BodyInserter#fromValue
.
.body(BodyInserters.fromValue(data))
或前一个的简写(这是最简单的)
.bodyValue(data)
推荐阅读
- pandas - 使用 matplotlib 和 pandas 制作 groupby 图
- api - HTTP 请求未经客户端身份验证方案“匿名”授权。从服务器收到的身份验证标头是“默认”。
- puppet - puppetserver 内存泄漏,为什么
- python - Tkinter 错误:_tkinter.TclError:未知选项“-1”
- docker - Docker swarm 无法增加网络池大小
- excel - 是否可以在 vba 中引用包含当前执行代码的工作表?
- python - 在熊猫数据框中提取城市、纬度和经度
- linux - Docker 在 Alpine 上安装 Heroku CLI
- python - 在应用程序运行时从任何命令/应用程序获取控制台输出
- multithreading - 多线程版本结果与非多线程版本不同