Friday, 27 April 2018

Using Spring RestTemplate for consuming Rest WebService



To simplify the REST service consumption Spring providers had introduced this Class called RestTemplate. This class is available in org.springframework.web.client package.

Maven dependency for this package

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.3.0.RELEASE</version>
</dependency>

A Example to use Spring REST template to consume REST web service with Basic Authentication.

package com.deploy.rest.jira;
/**
 * @author Kumar Gaurav
 *
 */

import java.util.Base64;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

/**
 * The Class SpringRestTemplateExample .
 */

@Service
public class SpringRestTemplateExample {

/**
* Jira rest call .
*
* @param uri
*            the uri
* @return the all jira issues specific to project
*/
public static void main(String args[]) {
try {
String url = "any rest url to connect to tool using basic authentication";
//Currently I am using JIRA REST web service call to retrieve all issues for specific project.
                        RestTemplate restTemplate = new RestTemplate();

HttpHeaders headers = createHttpHeaders("UserName", "Password");
HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);
ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
/**
* We can use like below in order to get desired pojo as return type
*/

/* ResponseEntity<JiraIssues> response = restTemplate.exchange(url, HttpMethod.GET, entity, JiraIssues.class);
  JiraIssues jiraIssues = response.getBody();*/

System.out.println("Result - status (" + response.getStatusCode() + ")");
System.out.println("Response.getBody():->" + response.getBody());

} catch (Exception e) {
e.printStackTrace();
}
}

/**
* This method will help to get the basic authentication.
*
* @param userName
* @param password
* @return
*/
private static HttpHeaders createHttpHeaders(String userName, String password) {
String beforeEncode = userName + ":" + password;
String authAfterEncode = Base64.getEncoder().encodeToString(beforeEncode.getBytes());
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.add("Authorization", "Basic " + authAfterEncode);
return headers;
}
}

No comments:

Post a Comment