如何将 Spring Web 客户端的内容类型设置为"application/json-patch+json"



我正在尝试向接受内容类型"的另一个API发出补丁休息请求;application/json补丁+json";。我正在使用Spring的Web客户端,但我还没能让它正常工作。我不断地得到";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 supportedntat org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping.handleNoMatch(RequestMappingInfoHandlerMapping.java:215)ntat org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.lookupHandlerMethod(AbstractHandlerMethodMapping.java:421)ntat org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.getHandlerInternal(AbstractHandlerMethodMapping.java:367)ntat 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的默认方式,所以您所需要做的就是正确地传入正文。以标准方式传递身体有几种方式。

或者通过传递生产者(可以是Mono或者Flux(。

.body(Mono.just(data))

使用CCD_ 4。

.body(BodyInserters.fromValue(data))

或者前一个的简写(这是最简单的(

.bodyValue(data)

最新更新