Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save DaddyMoe/53c4e8e412b00ad34523e4b27ea4e48c to your computer and use it in GitHub Desktop.
Save DaddyMoe/53c4e8e412b00ad34523e4b27ea4e48c to your computer and use it in GitHub Desktop.
Spring RestTemplate Basic Auth Example
public class SpringRestTemplateBasicAuthExample {
public static void main(String... args){
RestTemplate rt = new RestTemplate();
rt.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
rt.getMessageConverters().add(new StringHttpMessageConverter());
String uri = new String("https://some.api.provider.com/rest/authenticate");
String plainCreds = "user@awesome.com:sfdfsdf$%&^$%4";
byte[] plainCredsBytes = plainCreds.getBytes();
byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
String base64Creds = new String(base64CredsBytes);
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", "Basic " + base64Creds);
HttpEntity<String> request = new HttpEntity<String>(headers);
ResponseEntity<String> response = rt.exchange(uri, HttpMethod.POST, request, String.class);
log.info("Account Content:" + response.getBody());
}
}
@zenglian
Copy link

I just saw this:

restTemplate.getInterceptors().add(new BasicAuthorizationInterceptor("user", "password"));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment