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 = "http://example.com/restful/endpoint";
Map myMap = new HashMap();
myMap.put("field1","value1");
...

//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);
headers.setContentType(MediaType.APPLICATION_JSON);

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

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

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s