Skip to main content

Jersey Framework Client - How to add HTTP Basic Authentication Header to HTTP Request?


Introduction

In this tutorial, we will learn how to add HTTP basic authorization token to the HTTP request header.

We will use Jersey Framework to consume RESTful web services. Read the following post if you want to learn how to secure web services using HTTP Basic Authentication

Jersey Java Framework - How to add HTTP Basic Authentication to RESTful web services?

Maven Dependencies

<dependency>
    <groupId>org.glassfish.jersey.core</groupId>
    <artifactId>jersey-client</artifactId>
    <version>2.29</version> 
</dependency>
 <dependency>
    <groupId>org.glassfish.jersey.inject</groupId>
    <artifactId>jersey-hk2</artifactId>
    <version>2.29</version>
</dependency>

Basic Authentication

is the most simple way to secure HTTP requests. It has the following format

Authorization: Basic base64-encoding of username:password

Jersey Client

Jersy is the reference implementation of JAX-RS. JAX-RS makes it very easy for Java developers to develop and consume RESTFul web services.

There are different ways To add basic authorization token to HTTP request, we will cover the following two ways
  • HttpAuthenticationFeature.basic("user", "password")
  • ClientConfig clientConfig = new ClientConfig();clientConfig.register(HttpAuthenticationFeature.basic("user", "password"));

Complete Code

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.Response;
import org.glassfish.jersey.client.ClientConfig;
import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature;

public class HTTPBasicAuthentication {

public static String GET_HTTP_URL = "RESTful web services URL";

public static void main(String[] args) throws Exception {

Client client = getClient();
//OR using ClientConfig i.e. getClientUsingClientConfig()

WebTarget webTarget = client.target(GET_HTTP_URL).path("");

Invocation.Builder builder = webTarget.request();

Response response = builder.get();

System.out.println(response.toString());
}

private static Client getClient() {

Client client = ClientBuilder.newClient();
client.register(HttpAuthenticationFeature.basic("user", "password"));
return client;
}

private static Client getClientUsingClientConfig() {

ClientConfig clientConfig = new ClientConfig();
clientConfig.register(HttpAuthenticationFeature.basic("user", "password"));
return ClientBuilder.newClient(clientConfig);
}
}

Conclusion

In this tutorial, we learned how to add Basic Authorization token to HTTP request header using Jersey client.

Happy learning.





Comments