$show=/label

HttpClient 4 – Get the Status Code Example

SHARE:

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.


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.

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:

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.


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

COMMENTS

BLOGGER

About Us

Author: Venkatesh - I love to learn and share the technical stuff.
Name

accumulo,1,ActiveMQ,2,Adsense,1,API,37,ArrayList,18,Arrays,24,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,8,Collections,37,Collector,1,Command Line,1,Comparator,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,149,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,38,Dictionary,1,Difference,2,Download,1,Eclipse,3,Efficiently,1,Error,1,Errors,1,Exceptions,8,Fast,1,Files,17,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,9,Grant,1,Grep,1,HashMap,2,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,6,Iterate,2,Jackson API,3,Java,32,Java 10,1,Java 11,6,Java 12,5,Java 13,2,Java 14,2,Java 8,128,Java 8 Difference,2,Java 8 Stream Conversions,4,java 8 Stream Examples,12,Java 9,1,Java Conversions,14,Java Design Patterns,1,Java Files,1,Java Program,3,Java Programs,114,Java Spark,1,java.lang,4,java.util. function,1,JavaScript,1,jQuery,1,Kotlin,11,Kotlin Conversions,6,Kotlin Programs,10,Lambda,2,lang,29,Leap Year,1,live updates,1,LocalDate,1,Logging,1,Mac OS,3,Math,1,Matrix,6,Maven,1,Method References,1,Mockito,1,MongoDB,3,New Features,1,Operations,1,Optional,6,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,2,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,31,String,61,String Programs,28,String Revese,1,StringBuilder,1,Swing,1,System,1,Tags,1,Threads,11,Tomcat,1,Tomcat 8,1,Troubleshoot,26,Unix,3,Updates,3,util,5,While Loop,1,
ltr
item
JavaProgramTo.com: HttpClient 4 – Get the Status Code Example
HttpClient 4 – Get the Status Code Example
A quick guide to get the status code in the HttpClient API. getStatusLine().getStatusCode() Example and related errors.
JavaProgramTo.com
https://www.javaprogramto.com/2020/04/httpclient-status-code.html
https://www.javaprogramto.com/
https://www.javaprogramto.com/
https://www.javaprogramto.com/2020/04/httpclient-status-code.html
true
3124782013468838591
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content