Using Spring’s RestTemplate to call RESTful web service with authentication

In most of my projects, I’ve always consumed SOAP web services via client jars generated from WSDL.

Lately we have seen more RESTful services surface in our projects, and Spring’s RestTemplate is an alternative to HttpClient that makes it easy to call the web service in your Java code.

Here’s an example with basic auth:

RestTemplate restTemplate = new RestTemplate();

String url = "";
Map myMap = new HashMap();

//setting headers because I need basic auth
HttpHeaders headers = new HttpHeaders();

// serialization time
String plainCreds = "username:password";
byte[] plainCredsBytes = plainCreds.getBytes();
byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
String base64Creds = new String(base64CredsBytes);

// stick the auth info into header
headers.add("Authorization", "Basic " + base64Creds);

//set your entity to send
HttpEntity entity = new HttpEntity(myMap, headers);

// send it!
ResponseEntity<String> out =, HttpMethod.POST, entity
, String.class);


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s