Enterprise Java

HttpClient 4 API – Get the Status Code -getStatusLine().getStatusCode() Example

A quick guide to get the status code in the HttpClient API. getStatusLine().getStatusCode() Example and related errors.

1. Introduction

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

2. Maven Dependencies

The following jars are required to run this HttiClient application.

commons-logging is internally is being used by other jars. Please do not forget to add these jars else you will get compile-time and runtime errors.

<dependency>
    <groupId>commons-logging</groupId>
    <artifactId>commons-logging</artifactId>
    <version>1.2</version>
</dependency>

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.12</version>
</dependency>

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpcore</artifactId>
    <version>4.4.13</version>
</dependency>

Error:

If you miss commons-logging jar then below exception will be produced.

1
2
3
4
5
6
7
8
9
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory
 at org.apache.http.conn.ssl.DefaultHostnameVerifier.<init>(DefaultHostnameVerifier.java:82)
 at org.apache.http.impl.client.HttpClientBuilder.build(HttpClientBuilder.java:966)
 at com.java.w3schools.blog.HttpClient.HttpClientGetStatusCode.main(HttpClientGetStatusCode.java:21)
Caused by: java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory
 at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:583)
 at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
 at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
 ... 3 more

3. Retrieve the Status Code from the Http Response

Once the HTTP Request is sent and after processing response will be sent back to the caller.

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package com.java.w3schools.blog.HttpClient;
 
import java.io.IOException;
 
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
 
public class HttpClientGetStatusCode {
 
 private static final String GOOGLE_URL = "http://www.google.com";
 
 private static CloseableHttpClient instance;
 
 private static CloseableHttpResponse response;
 
 public static void main(String[] args) throws ClientProtocolException, IOException {
  HttpGet httpGet = new HttpGet(GOOGLE_URL);
  instance = HttpClientBuilder.create().build();
 
  response = instance.execute(httpGet);
 
  System.out.println("response.getStatusLine() :: " + response.getStatusLine());
  final int statusCode = response.getStatusLine().getStatusCode();
 
  int code = HttpStatus.SC_OK;
 
  if (code == statusCode) {
 
   System.out.println("Status Code  : " + code);
  } else {
   System.out.println("StatusCode not 200  : " + code);
  }
 
 }
 
}

The returned response type of org.apache.http.HttpResponse which allows us to get the status of execution of the request. getStatusLine() method returns StatusLine object which holds the status of the request. use
getStatusCode() to get only execution code.

Output:

1
2
response.getStatusLine() :: HTTP/1.1 200 OK
Status Code  : 200

4. Exception if URL is down

If the given URL is down or wrong then we will get UnknownHostException runtime exception.

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
Exception in thread "main" java.net.UnknownHostException: www.google.com1: nodename nor servname provided, or not known
 at java.base/java.net.Inet6AddressImpl.lookupAllHostAddr(Native Method)
 at java.base/java.net.InetAddress$PlatformNameService.lookupAllHostAddr(InetAddress.java:929)
 at java.base/java.net.InetAddress.getAddressesFromNameService(InetAddress.java:1515)
 at java.base/java.net.InetAddress$NameServiceAddresses.get(InetAddress.java:848)
 at java.base/java.net.InetAddress.getAllByName0(InetAddress.java:1505)
 at java.base/java.net.InetAddress.getAllByName(InetAddress.java:1364)
 at java.base/java.net.InetAddress.getAllByName(InetAddress.java:1298)
 at org.apache.http.impl.conn.SystemDefaultDnsResolver.resolve(SystemDefaultDnsResolver.java:45)
 at org.apache.http.impl.conn.DefaultHttpClientConnectionOperator.connect(DefaultHttpClientConnectionOperator.java:112)
 at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.connect(PoolingHttpClientConnectionManager.java:376)
 at org.apache.http.impl.execchain.MainClientExec.establishRoute(MainClientExec.java:393)
 at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:236)
 at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:186)
 at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:89)
 at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:110)
 at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:185)
 at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:83)
 at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:108)
 at com.java.w3schools.blog.HttpClient.HttpClientGetStatusCode.main(HttpClientGetStatusCode.java:24)

5. Conclusion

In this article, We’ve seen how to get the status code for a HttpClient request.

As usual, The example shown in this article is on Github.

GitHub Code

Published on Java Code Geeks with permission by Venkatesh, partner at our JCG program. See the original article here: HttpClient 4 API – Get the Status Code – getStatusLine().getStatusCode() Example

Opinions expressed by Java Code Geeks contributors are their own.

Subscribe
Notify of
guest

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

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button