Description
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.