Spring Restful client’s overview
We have learned about how to develop the Rest services for JSON and XML data representation in the previous articles and also we have consumed these Rest services using Rest Client tool (advanced Rest client).
Accessing Rest services through Rest client tools is not so useful in real-time, we need to provide a way to access them progrmatically to get the benefit of it in Real time.
Let’s learn about how to consume these Rest services programtically.
Java provides HttpClient to consume the rest services programtically.
spring provides RestTemplate to achieve the same.
HTTP Client API is a Java based framework for communicating with Rest Web Services.
It can be used to call rest service as below
- String url = " http://localhost:8080/RestWithHttpClient/rest/userInfo ";
- CloseableHttpClient httpClient = HttpClients.createDefault();
- HttpGet getRequest = new HttpGet(url);
- getRequest.addHeader("accept", "application/xml");
- HttpResponse response = httpClient.execute(getRequest);
String url = " http://localhost:8080/RestWithHttpClient/rest/userInfo "; CloseableHttpClient httpClient = HttpClients.createDefault(); HttpGet getRequest = new HttpGet(url); getRequest.addHeader("accept", "application/xml"); HttpResponse response = httpClient.execute(getRequest);
For complete sample project using HttpClient, please check this article
Spring provides many Template classes like JdbcTemplate,HibernateTemplate by encapsulating boiler plate code inside these Template classes.
As a developer we just need to use these spring template classes to get more functionality with minimal code.
RestTemplate is one among such template classes which is mainly developed for calling Rest services with different HTTP methods(GET,POST etc) and different data representations(XML,JSON etc).
Internally Rest template uses HttpMessageConverter instances to convert HTTP messages to and from POJO classes.
Converters for the main mime types are registered automatically by spring but we can also register additional converters via
setMessageConverters(List< org.springframework.http.converter.HttpMessageConverter< ?>>).
Spring Rest template Methods for HTTP methods are as below