Posted In: Spring, Spring REST

Spring Rest Template – BasicAuthorizationInterceptor Example

Usecase

Call to the service needs basic authorization headers. You need not set these headers in each request separately but achieve it by one single BasicAuthorizationInterceptor

 

package com.example;

import org.springframework.http.ResponseEntity;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.support.BasicAuthorizationInterceptor;
import org.springframework.web.client.RestTemplate;

public class RestTmpltBasic {
	public static void main(String[] args) {
		new RestTmpltBasic().proceed();
	}

	public void proceed() {
		System.out.println(
		        "RestTmpltBasic::proceed() started");
		ClientHttpRequestInterceptor bi = new BasicAuthorizationInterceptor(
		        "username", "password");
		RestTemplate rt = new RestTemplate();
		rt.getInterceptors().add(bi);
		ResponseEntity<String> re = rt.getForEntity(
		        "http://localhost:8080/Example201726/time/30",
		        String.class);
		try {
			String body = re.getBody();
			System.out.println(body);
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println(
		        "RestTmpltBasic::proceed() ends");
	}
}

Output. Observe Basic authorization header being added to the request

Basic dXNlcm5hbWU6cGFzc3dvcmQ=

by , on July 21st, 2017

  • Categories