From RestClient.ResponseSpec
:
/**
* ...
* @return the body, or {@code null} if no response body was available
*/
@Nullable
<T> T body(Class<T> bodyType);
Calling an API with the following:
restClient
.get()
.uri("/api/v1/pokemon/{id}", id)
.accept(MediaType.APPLICATION_JSON)
.retrieve()
.body(Pokemon.class);
If I stub out an endpoint with WireMock as an OK application/json response with no body:
wireMock.stubFor(get(urlEqualTo("/api/v1/pokemon/123")).willReturn(okJson(null)));
I get an exception:
org.springframework.web.client.RestClientException: Error while extracting response for type [com.example.Pokemon] and content type [application/json]
Caused by: org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: No content to map due to end-of-input
Or stubbing it out as just OK:
wireMock.stubFor(get(urlEqualTo("/api/v1/pokemon/123")).willReturn(ok()));
I get different exception:
org.springframework.web.client.UnknownContentTypeException: Could not extract response: no suitable HttpMessageConverter found for response type [class com.example.Pokemon] and content type [application/octet-stream]
Expected: null is returned as documented when no response body is returned, at least in the okJson(null)
case (I suspect WireMock is defaulting to an octet body in the latter case...)
Alternatively: ResponseSpec.body()
is not nullable and is documented as throwing an exception in the case no body is available
Using okJson("null")
seems to work and null is returned, but that is an available response body. This is in contrast to WebClient's blockOptional()
which did return an empty Optional
for okJson(null)
and block()
which returns null.
Comment From: josephearl
Using okJson("null")
seems to work and null is returned, but that is an available response body
Comment From: josephearl
This is contract to WebClient's blockOptional()
which did return an empty Optional
for okJson(null)
Comment From: poutsma
~~Would you mind putting the code into a sample project that we can unzip or git clone, build, and deploy, and that reproduces the problem?~~
Never mind, I was able to reproduce it without WireMock.
Comment From: poutsma
This is related to #12671, so it seems fitting that we adopt the same solution as used for RestTemplate, see b6675b6167f3580fcc03b8d725db482e1e2e44e7.
Comment From: poutsma
Fixed, thanks for reporting this!