I'm using Spring RestTemplate to consume REST service with basic authentication, so I need a way to set the username and password. After running some searches, it turns out that it's not that easy to set the username and password directly. So I manually created the Authorization header.

import org.apache.commons.codec.binary.Base64;

HttpHeaders headers = new HttpHeaders();  
headers.set("Authorization", "Basic " + new String(Base64.encodeBase64((username + ":" + password).getBytes(Charset.forName("US-ASCII")))));  
HttpEntity<byte[]> entity = new HttpEntity<byte[]>(headers);  
ResponseEntity<byte[]> response = restTemplate.exchange(uri, HttpMethod.valueOf(httpMethod), entity, byte[].class);