How to check the Http Response status code of Java HttpResponse

Last modified date

Comments: 0

Contents

Problem

When making a HttpRequest in Java using the HttpRequest.Builder, the send function returns a HttpResponse.

The HttpResponse object returned does allow you to get the response code, but since there are many http response codes, we would have to have a lot of code to handle every response code.

But what if just want to know if the request was successful?

The Spring framework has a useful function to call if to get the response codes for a particular set of responses.

Solution

Let’s assume you make a http request and get back a HttpResponse object:

HttpResponse<String> response = httpClientBuilder.send(request, HttpResponse.BodyHandlers.ofString());

To check whether this response was successful, we can perform a check to see if the response was in the 200 – 299 range, meaning it was successful.

This can be done using the HttpStatus.valueOf function in Spring:

HttpStatus.valueOf(httpResponse.statusCode()).is2xxSuccessful()

This function will take the http response and see whether the response code begins with a 2 (2xx) meaning it was successful and return a boolean.

So it can be used in an if statement like this:

if (HttpStatus.valueOf(httpResponse.statusCode()).is2xxSuccessful()) {
   // the request was successful
}

This is a quick and convenient way to check whether the response was successful without having to check every 2xx response code.

The same operation can be performed for the other http response codes such as 3xx, 4xx, 5xx, more info can be found in the java docs.

This means that you can have a catch all logic for the different error response types, rather than having to check for every http response code.

JakTech

Leave a Reply

Your email address will not be published. Required fields are marked *

Post comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.