Java resttemplate get request

Spring Boot RestTemplate GET Example

In this, Spring Boot RestTemplate GET request example, learn to use RestTemplate to invoke HTTP GET API and verify the response status code and the response entity body.

To create the rest APIs, use the sourcecode provided in spring boot 2 rest api example.

Start with including the latest version of spring-boot-starter-web dependency in the project.

 org.springframework.boot spring-boot-starter-web 

In the given example, I will first write the rest API code and then write the unit test which invokes the rest API and verifies the API response.

@GetMapping("users") public ResponseEntity> getAll() < . >@GetMapping("users/") public ResponseEntity getById(@PathVariable long id)

The simplest way to create a RestTemplate instance is its default constructor.

RestTemplate restTemplate = new RestTemplate();

Alternatively, we can use RestTemplateBuilder to configure a custom instance and later autowire into other beans.

@Bean public RestTemplate restTemplate(RestTemplateBuilder builder)

The RestTemplate provides the following methods for executing GET APIs:

  • getForObject() – retrieves a representation by doing a GET on the URL. The response (if any) is unmarshalled to the given class type and returned.
  • getForEntity() – retrieve a representation as ResponseEntity by doing a GET on the URL.
  • exchange() – execute the specified HttpEntity and return the response as ResponseEntity.
  • execute()– execute the HttpMethod to the given URI template, prepare the request with the RequestCallback, and read the response with a ResponseExtractor.

The getForEntity() method returns a ResponseEntity that can be used to check the response status, headers and body. In following example, we are retrieving the response as String and parsing it later.

String userJson = restTemplate.getForObject("/users/", String.class, Map.of("id", "1")); ResponseEntity responseEntity = restTemplate.getForEntity("/users/", String.class, Map.of("id", "1")); ObjectMapper mapper = new ObjectMapper(); JsonNode root = mapper.readTree(responseEntity.getBody()); 

If we want to retrieve the response as POJO, we can do it as follows:

//User Collection User[] usersArray = restTemplate.getForObject("/users", User[].class); ResponseEntity responseEntity = restTemplate.getForEntity("/users", User[].class); // User by Id User user = restTemplate.getForObject("/users/", User.class, Map.of("id", "1")); ResponseEntity responseEntityUser = restTemplate.getForEntity("/users/", User.class, Map.of("id", "1"));

If the GET API accepts request headers, we need to use the generic exchange() API. In this example, we are sending two headers. X-COM-PERSIST header is mandatory and X-COM-LOCATION is optional. The example invokes GET API with mandatory headers and verifies the API response code and the response body.

HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); headers.set("X-COM-PERSIST", "NO"); headers.set("X-COM-LOCATION", "USA"); HttpEntity entity = new HttpEntity(headers); ResponseEntity responseEntity = restTemplate.exchange("/users", HttpMethod.GET, entity, User[].class);

Let me know if you have any queries in this spring boot RestTemplate get API example.

Источник

How to make HTTP requests using RestTemplate in Spring Boot

The RestTemplate class in Spring Framework is a synchronous HTTP client for making HTTP requests to consume RESTful web services. It exposes a simple and easy-to-use template method API for sending an HTTP request and handling the HTTP response.

The RestTemplate class also provides aliases for all supported HTTP request methods, such as GET, POST, PUT, DELETE, and OPTIONS.

In this tutorial, we will learn how to use the Spring REST client — RestTemplate — for sending HTTP requests in a Spring Boot application.

Since the RestTemplate class is a part of the Spring Web project, we only need the spring-boot-starter-web dependency. Add the following dependency to your Gradle project’s build.gradle file:

implementation 'org.springframework.boot:spring-boot-starter-web' 
dependency> groupId>org.springframework.bootgroupId> artifactId>spring-boot-starter-webartifactId> dependency> 

Let’s start with a simple example to retrieve a list of posts using RestTemplate’s getForObject() method: RestService.java

@Service public class RestService  private final RestTemplate restTemplate; public RestService(RestTemplateBuilder restTemplateBuilder)  this.restTemplate = restTemplateBuilder.build(); > public String getPostsPlainJSON()  String url = "https://jsonplaceholder.typicode.com/posts"; return this.restTemplate.getForObject(url, String.class); > > 

Notice the response returned by the getForObject() method. It is a plain JSON string. We can easily parse this JSON string into an object using Jackson.

public class Post implements Serializable  private int userId; private int id; private String title; private String body; // getters and setters > 
public Post[] getPostsAsObject()  String url = "https://jsonplaceholder.typicode.com/posts"; return this.restTemplate.getForObject(url, Post[].class); > 
String url = "https://jsonplaceholder.typicode.com/posts?userId=2"; 
public Post getPostWithUrlParameters()  String url = "https://jsonplaceholder.typicode.com/posts/"; return this.restTemplate.getForObject(url, Post.class, 1); > 

If you want to manipulate the response (like checking HTTP status code), use the getForEntity() method like below:

public Post getPostWithResponseHandling()  String url = "https://jsonplaceholder.typicode.com/posts/"; ResponseEntityPost> response = this.restTemplate.getForEntity(url, Post.class, 1); if(response.getStatusCode() == HttpStatus.OK)  return response.getBody(); > else  return null; > > 

If you want to set the request headers like content-type , accept , or any custom header, use the generic exchange() method:

public Post getPostWithCustomHeaders()  String url = "https://jsonplaceholder.typicode.com/posts/"; // create headers HttpHeaders headers = new HttpHeaders(); // set `accept` header headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); // set custom header headers.set("x-request-source", "desktop"); // build the request HttpEntity request = new HttpEntity(headers); // use `exchange` method for HTTP call ResponseEntityPost> response = this.restTemplate.exchange(url, HttpMethod.GET, request, Post.class, 1); if(response.getStatusCode() == HttpStatus.OK)  return response.getBody(); > else  return null; > > 

A POST request is used to create a new resource. The RestTemplate class offers several template methods like postForObject() , postForEntity() , and postForLocation() for making POST request. The first two methods are similar to what we discussed above for the response format. The last method returns the location of the newly created resource instead of the complete resource. Let us make use of the postForEntity() method to create a new post:

public Post createPost()  String url = "https://jsonplaceholder.typicode.com/posts"; // create headers HttpHeaders headers = new HttpHeaders(); // set `content-type` header headers.setContentType(MediaType.APPLICATION_JSON); // set `accept` header headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); // create a map for post parameters MapString, Object> map = new HashMap>(); map.put("userId", 1); map.put("title", "Introduction to Spring Boot"); map.put("body", "Spring Boot makes it easy to create stand-alone, production-grade Spring based Applications."); // build the request HttpEntityMapString, Object>> entity = new HttpEntity>(map, headers); // send POST request ResponseEntityPost> response = this.restTemplate.postForEntity(url, entity, Post.class); // check response status code if (response.getStatusCode() == HttpStatus.CREATED)  return response.getBody(); > else  return null; > > 
public Post createPostWithObject()  String url = "https://jsonplaceholder.typicode.com/posts"; // create headers HttpHeaders headers = new HttpHeaders(); // set `content-type` header headers.setContentType(MediaType.APPLICATION_JSON); // set `accept` header headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); // create a post object Post post = new Post(1, "Introduction to Spring Boot", "Spring Boot makes it easy to create stand-alone, production-grade Spring based Applications."); // build the request HttpEntityPost> entity = new HttpEntity>(post, headers); // send POST request return restTemplate.postForObject(url, entity, Post.class); > 

Quick Guide: Check out RestTemplate POST Request with JSON and Headers for more POST request examples.

public void updatePost()  String url = "https://jsonplaceholder.typicode.com/posts/"; // create headers HttpHeaders headers = new HttpHeaders(); // set `content-type` header headers.setContentType(MediaType.APPLICATION_JSON); // set `accept` header headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); // create a post object Post post = new Post(4, "New Title", "New Body"); // build the request HttpEntityPost> entity = new HttpEntity>(post, headers); // send PUT request to update post with `id` 10 this.restTemplate.put(url, entity, 10); > 

The put() method does not return anything. If you want to process the response, use the generic exchange() method instead:

public Post updatePostWithResponse()  String url = "https://jsonplaceholder.typicode.com/posts/"; // create headers HttpHeaders headers = new HttpHeaders(); // set `content-type` header headers.setContentType(MediaType.APPLICATION_JSON); // set `accept` header headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); // create a post object Post post = new Post(4, "New Title", "New Body"); // build the request HttpEntityPost> entity = new HttpEntity>(post, headers); // send PUT request to update post with `id` 10 ResponseEntityPost> response = this.restTemplate.exchange(url, HttpMethod.PUT, entity, Post.class, 10); // check response status code if (response.getStatusCode() == HttpStatus.OK)  return response.getBody(); > else  return null; > > 
public void deletePost()  String url = "https://jsonplaceholder.typicode.com/posts/"; // send DELETE request to delete post with `id` 10 this.restTemplate.delete(url, 10); > 
public HttpHeaders retrieveHeaders()  String url = "https://jsonplaceholder.typicode.com/posts"; // send HEAD request return this.restTemplate.headForHeaders(url); > 
public SetHttpMethod> allowedOperations()  String url = "https://jsonplaceholder.typicode.com/posts"; // send HEAD request return this.restTemplate.optionsForAllow(url); > 

If there is an error during the request execution or the server returns a non-successful HTTP error (4xx or 5xx), RestTemplate will throw an exception. You can catch the HttpStatusCodeException in the catch block to get the response body and headers:

public String unknownRequest()  try  String url = "https://jsonplaceholder.typicode.com/404"; return this.restTemplate.getForObject(url, String.class); > catch (HttpStatusCodeException ex)  // raw http status code e.g `404` System.out.println(ex.getRawStatusCode()); // http status code e.g. `404 NOT_FOUND` System.out.println(ex.getStatusCode().toString()); // get response body System.out.println(ex.getResponseBodyAsString()); // get http headers HttpHeaders headers= ex.getResponseHeaders(); System.out.println(headers.get("Content-Type")); System.out.println(headers.get("Server")); > return null; > 

Quick Guide: Learn more about handling errors while using the RestTemplate in a Spring Boot application.

There are two types of timeouts: connection timeout and read timeout. By default, RestTemplate has infinite timeouts. But we can change this behavior by using the RestTemplateBuilder class for setting the connection and read timeouts:

public RestService(RestTemplateBuilder restTemplateBuilder)  // set connection and read timeouts this.restTemplate = restTemplateBuilder .setConnectTimeout(Duration.ofSeconds(500)) .setReadTimeout(Duration.ofSeconds(500)) .build(); > 

That’s all for using Spring Framework’s RestTemplate class to call remote RESTful web services in a Spring Boot application. We talked about almost all HTTP verbs and used RestTemplate to make requests for all of them. If you are interested in learning more, check out the processing JSON data in Spring Boot guide. It will introduce you to Jackson, which is used with RestTemplate for parsing unknown JSON data. Read Next: RestTemplate Basic Authentication Example ✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like.

Источник

Читайте также:  Настройка cron запуск php
Оцените статью