如何将 Spring Webclient 的内容类型设置为 "application/json-patch+json"

How do I set Content type for Spring Webclient to "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 中实际发送的内容具有优先权。在您的代码中,您声明以下内容以发送 body.

.body(BodyInserters.fromFormData("lastKnownState", state))

这表明你发送的是表单数据,这是一种键值发送数据的方式,然后webclient会自动为你设置内容类型header为x-www-form-urlencoded.

如果您想要 json 内容类型 header,则需要发送 json 数据。发送 json 是 webclient 的默认方式,因此您需要做的就是正确传递 body 。有几种方法可以以标准方式传递 body。

通过生产者(可以是 MonoFlux)。

.body(Mono.just(data))

使用 BodyInserter#fromValue.

.body(BodyInserters.fromValue(data))

或者前一个的shorthand(最简单)

.bodyValue(data)