Monday, March 2, 2020

RestTemplate in Spring

RestTemplate in Spring

I needed "RestTemplate (Spring Boot) with HTTP GET method" to connect with vimeo.com last week.

We can use:

    getForObject(url, classType) – retrieve a representation by doing a GET on the URL. The response (if any) is unmarshalled to given class type and returned.
    getForEntity(url, responseType) – retrieve a representation as ResponseEntity by doing a GET on the URL.
    exchange(requestEntity, responseType) – execute the specified request and return the response as ResponseEntity.
    execute(url, httpMethod, requestCallback, responseExtractor) – execute the httpMethod to the given URI template, preparing the request with the RequestCallback, and reading the response with a ResponseExtractor.

An example:
final String url = "http://localhost:8080/resources.json";
    RestTemplate restTemplate = new RestTemplate();
    String result = restTemplate.getForObject(url, String.class);

Sources:
https://spring.io/guides/gs/rest-service/

https://howtodoinjava.com/spring-boot2/resttemplate/spring-restful-client-resttemplate-example/

No comments: