I just announced the new Spring 5 modules in REST With Spring:

>> CHECK OUT THE COURSE

1. Overview

In this very quick tutorial, I will show how to get and validate the StatusCode of the HTTP Response using HttpClient 4.

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.http.HttpResponse – which allows us to access the status line of the response, and implicitly the Status Code:

response.getStatusLine().getStatusCode()

Using this, we can validate that the code we receive from the server is indeed correct:

@Test
public void givenGetRequestExecuted_whenAnalyzingTheResponse_thenCorrectStatusCode() 
  throws ClientProtocolException, IOException {
    HttpClient client = HttpClientBuilder.create().build();    
    HttpResponse response = client.execute(new HttpGet(SAMPLE_URL));
    int statusCode = response.getStatusLine().getStatusCode();
    assertThat(statusCode, equalTo(HttpStatus.SC_OK));
}

Notice that we’re using the predefined Status Codes also available in the library via org.apache.http.HttpStatus.

3. Conclusion

This very simple example shows how to retrieve and work with Status Codes with the Apache HttpClient 4.

The implementation of all these examples and code snippets can be found in my github project – this is an Eclipse based project, so it should be easy to import and run as it is.

I just announced the new Spring 5 modules in REST With Spring:

>> CHECK OUT THE LESSONS

Sort by:   newest | oldest | most voted
ChangWonSon
Guest

I have question

two type http connection
1. HttpURLConnection http = (HttpURLConnection)url.openConnection();

2. HttpClient client = HttpClientBuilder.create().build();

which is better?? and why?

Eugen Paraschiv
Guest

Hey Chang – so, the HttpURLConnection is a low level connection from the old java.net package, whereas the HttpClient is a higher level API. The difference is mainly in convenience of use – for most things you’ll want to use the client, not the low level connection. Now – Java 9 is scheduled to address this as well with a new Http Client implementation – but until then the Apache client is your best bet. Hope that helps. Cheers,

Eugen.

ChangWonSon
Guest

thank you for your comment~!
Always read your new article and very helpful

Eugen Paraschiv
Guest

No worries, glad you’re enjoying the new articles. Cheers.

wpDiscuz