Neo
Neo

Reputation: 2049

Receive Spring ResponseEntity with and without body

How to implement a REST call which can sometimes return no body?

My SpringBoot application calls an external service over REST HTTP and its implemented via the org.springframework.web.client Client and method public <T> ResponseEntity<T> exchange.

The client received till now always a String body -> ResponseEntity<String>. Some time ago the service we are calling returns us HTTP 202 without body, so the following exception is thrown:

java.lang.IllegalArgumentException: argument "content" is null.

How can I tell Spring to ignore the body for a 202 status code?

Upvotes: 1

Views: 2469

Answers (1)

Gregor Zurowski
Gregor Zurowski

Reputation: 2346

You can use Void as the generic type parameter for ResponseEntity if the service does not return a response body:

ResponseEntity<Void> response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, Void.class)

If the service returns a response sometimes, you could handle the response as a String. For empty responses, you would receive an empty string. For non-empty responses, you would need to deserialize the returned payload yourself.

ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class)
if (Strings.isEmpty(res.getBody())) {
    // handle empty response
} else {
    // handle non-empty response
}

Upvotes: 0

Related Questions