[英]PATCH with contentType application/json instead of 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 Unsupported media type”
我試過以下;
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 的默認方式,因此您需要做的就是正確傳遞正文。 有幾種方法可以以標准方式傳遞身體。
通過傳遞生產者(可以是Mono
或Flux
)。
.body(Mono.just(data))
使用BodyInserter#fromValue
。
.body(BodyInserters.fromValue(data))
或前一個的簡寫(這是最簡單的)
.bodyValue(data)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.