Let's get started with a Microservice Architecture with Spring Cloud:
Apache HttpClient – Get the Status Code
Last updated: June 28, 2023
1. Overview
In this very quick tutorial, I will show how to get and validate the StatusCode of the HTTP Response using HttpClient.
If you want to dig deeper and learn other cool things you can do with the HttpClient – head on over to the main HttpClient tutorial.
2. Retrieve the Status Code from the Http Response
After sending the Http request – we get back an instance of org.apache.hc.client5.http.impl.classic.ClosableHttpResponse – which allows us to access directly the Status Code:
response.getCode()
Using this, we can validate that the code we receive from the server is indeed correct:
@Test
public final void givenGetRequestExecuted_whenAnalyzingTheResponse_thenCorrectStatusCode() throws IOException {
final HttpGet request = new HttpGet(SAMPLE_URL);
try (CloseableHttpClient client = HttpClientBuilder.create().build();
CloseableHttpResponse response = (CloseableHttpResponse) client
.execute(request, new CustomHttpClientResponseHandler())) {
assertThat(response.getCode(), equalTo(HttpStatus.SC_OK));
}
}
Notice that we’re using the predefined Status Codes also available in the library via org.apache.hc.core5.http.HttpStatus.
3. Conclusion
This very simple example shows how to retrieve and work with Status Codes with the Apache HttpClient.
The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
















