How to set Basic Authorization Header with RestTemplate

Usually, when you invoke some REST endpoint, you'll need some sort of authorization. In this example, we'll show how to invoke endpoint protected with a Basic authorization that should create a car and return created object with RestTemplate in Spring.

Basic authorization structure looks as follows:

Authorization: Basic <Base64EncodedCredentials>

Base64EncodedCredentials here represent Base64 encoded String composed od username and password separated by a colon:

username:password

When you're using RestTemplate as injected bean, it's a bit inflexible, so in this example, we'll be creating RestTemplate manually. You can also use RestTemplateFactory or whatever other methods you prefer:

public Car createCar(Car car){

String username = "username";
String password = "password";
String credentials = username+":"+password;
byte[] credentialBytes = credentials .getBytes();
byte[] base64CredentialBytes = Base64.encodeBase64(credentialBytes);
String base64Credentials = new String(base64CredentialBytes);
RestTemplate restTemplate = new RestTemplate();
// create http headers and add authorization header we just created
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", "Basic " + base64Credentials );

HttpEntity<String> request = new HttpEntity<String>(headers);
String url = "http://localhost:8002/api/cars";
ResponseEntity<Car> response = restTemplate.exchange(url, HttpMethod.GET, request, Car.class);
return response.getBody();
}