Skip to main content

Working with request header in Jersey (JAX-RS) guide

In the previous post, we talked about, how to get parameters and their values from the request query string. In this guide learn how to get request header values in Jersey (JAX-RS) based application.

We had tested or used the following tools and technologies in this project:

  1. Jersey (v 2.21)
  2. Gradle Build System (v 2.9)
  3. Spring Boot (v 1.3)
  4. Java (v 1.8)
  5. Eclipse IDE

This is a part of Jersey (JAX-RS) Restful Web Services Development Guides series. Please read Jersey + Spring Boot getting started guide.

Gradle Build File

We are using Gradle for our build and dependency management (Using Maven rather than Gradle is a very trivial task).

File: build.gradle

buildscript {
    ext {
        springBootVersion = '1.3.0.RELEASE'
    }
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}") 
    }
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'spring-boot' 

jar {
    baseName = 'jersey-request-header'
    version = '0.0.1-SNAPSHOT'
}
sourceCompatibility = 1.8
targetCompatibility = 1.8

repositories {
    mavenCentral()
}

dependencies {
    compile('org.springframework.boot:spring-boot-starter-jersey')
    testCompile('org.springframework.boot:spring-boot-starter-test') 
}

eclipse {
    classpath {
         containers.remove('org.eclipse.jdt.launching.JRE\_CONTAINER')
         containers 'org.eclipse.jdt.launching.JRE\_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8'
    }
}

task wrapper(type: Wrapper) {
    gradleVersion = '2.7'
}

Spring Boot Main Method Class

Spring Boot Main Method Class is the starting point for the Spring Boot-based application just like a normal java application.

File: JerseyRequestParameterApplication.java

package in.geekmj;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class JerseyRequestHeaderApplication {

    public static void main(String\[\] args) {
        SpringApplication.run(JerseyRequestHeaderApplication.class, args);
    }
}

Jersey Configuration Class

Jersey Configuration class is a ResourceConfig class for providing Jersey-specific configuration and Resources entry.

File: JerseyConfig.java

package in.geekmj.config;

import javax.ws.rs.ApplicationPath;

import org.glassfish.jersey.server.ResourceConfig;
import org.springframework.stereotype.Component;

import in.geekmj.resource.RequestHeaderResource;

@Component
@ApplicationPath("/")
public class JerseyConfig extends ResourceConfig {

	/*
	 * In constructor we can define Jersey Resources & Other Components
	 */
	public JerseyConfig() {
		register(RequestHeaderResource.class);
	}
}

Reading specific request header using @HeaderParam

File: RequestParameterResource.java

package in.geekmj.resource;

import java.util.HashMap;
import java.util.Map;

import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;

@Path("/request-header")
@Produces(MediaType.APPLICATION\_JSON)
public class RequestHeaderResource {

	/*
	 * We can inject request header as an instance variables using @HeaderParam
	 */

	@HeaderParam("token")
	private String token;

	/* We can inject request header values in method using @HeaderParam */
	@GET
	public Map<String, String> getRequestHeaders(@HeaderParam("content-type") String contentType) {

		Map<String, String> requestHeaders = new HashMap<String, String>();
		requestHeaders.put("token", token);
		requestHeaders.put("contentType", contentType);
		return requestHeaders;
	}

}

We have used @HeaderParam for injecting specific request headers as instance variables and method parameters.

API URI /request-header can read two headers:

  1. token
  2. content-type

In response to this API URI, we show values for these header parameters in JSON structure.

Start Spring Boot Application and test the API using Postman. In Postman we can pass headers. (Refer Spring Boot quick starter guide to understand how to start Spring Boot Application)

Test https://localhost:8080/request-header as shown below in Postman.

!Getting Jersey Request Header Values Getting Jersey Request Header Values

Get all request headers in Map

File: RequestParameterResource.java

package in.geekmj.resource;

import java.util.HashMap;
import java.util.Map;

import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;

@Path("/request-header")
@Produces(MediaType.APPLICATION\_JSON)
public class RequestHeaderResource {
	/*
	 * We can get a map of all request headers name and value using HttpHeaders
	 * context injection
	 */

	@SuppressWarnings("rawtypes")
	@GET
	@Path("/all")
	public Map getAllRequestHeadersUsingContext(@Context HttpHeaders headers) {
		return headers.getRequestHeaders();
	}
}

We had used @Context to inject HttpHeaders. HttpHeaders has a method getRequestHeaders which returns a map with Key as header name and value as a header value.

Test https://localhost:8080/request-header/all as shown below in Postman.

Jersey gets HTTP request all headers values

References

  1. What is the HTTP request header? (Wikipedia Article)

  2. Official Jersey Documentation

  3. Download the Full Project

  4. Follow Project On Github

Comments

Popular posts from this blog

Extend and reuse an existing AirByte destination connector

AirByte is an open-source ELT (Extract, Load, and Transformation) application. It heavily uses containerization for the deployment of its various components. On the local machine, we need docker to run it. AirByte has an impressive list of source and destination connectors available. One of my use case data destinations is the  ClickHouse data warehouse and its destination connector is not yet (2021-12-08) available. As per the documentation, It seems that creating a destination connector is a non-trivial job. It's a great idea to build an open-source ClickHouse destination connector. However, I tried avoiding the temptation to create one because of the required effort. AirByte has a  MySql destination connector available. ClickHouse provides a MySQL connector for access from any MySQL client. We need to configure Clickhouse to give support for the MySQL connector. Accessing ClickHouse from AirByte using its MySQL destination connector looks promising. However, when ...

Understanding Type Checking

A few examples of types in the context of programming language can be integer, float, character, string, array, etc.  When a program executes then data flow between instructions and values of specific types are assigned to a variable after some operation. It's important for the system to verify if the correct types are used as operands in operations. For e.g. In a sum operation, the expectation for operands to be of numeric type. The program's execution should fail in the case there is inconsistency. We can classify programming languages into two categories based as per their ability to cater to type safety: Dynamically Typed Language Statically Typed Language

Setting Clickhouse column data warehouse at Google Cloud Compute Engine VM

I didn't have a Google Cloud account associated with my email, so I signed up for one. It needs a valid Credit Card and mobile number to check if you are human. On successful sign up I get 300$ to spend within 3 months. Creating a free forever Google Cloud Compute Engine VM As per Google Cloud documentation you can have 1 non-preemptible e2-micro VM instance (1GB 2vCPU, 30GB Disk, etc.) per month free forever in some regions with some restrictions. I wanted the following stuff in my VM before I can install Clickhouse on to that: Ubuntu 20.x LTS SSH access from my machine Enabling SSH-based access to Google Compute Engine VM Step 1 Created an ssh private and public key on my mac using the following command ssh-keygen -t rsa -f ~/.ssh/gcloud-ssh-key -C mrityunjay -b 2048 Step 2 Copied the public key from the console using the following command: cat ~/.ssh/gcloud-ssh-key.pub output ssh-rsa <Gibrish :)> mrityunjay Step 3 I went to Google Cloud Console > Co...