Saturday, May 4, 2024
HomeJava10 Examples Of RestTemplate in Spring Framework, Spring Boot and Java

10 Examples Of RestTemplate in Spring Framework, Spring Boot and Java


For a very long time this was my go-to HTTP shopper as again then Java did not have any factor like that and most undertaking we labored used Spring. However, now, you can even use

in addition to new WebClient class from Spring Boot to make REST API Calss however nonetheless, this class continues to be fairly vital and on this article, I’ll present you how one can use RestTemplate successfully in Java. 

However, , Earlier than we get to the ten finest examples that can train you every part there may be to know concerning the RestTemplate in Spring, let me let you know a bit bit extra about what it truly is.

10 Examples Of RestTemplate In Spring

In
Spring, the RestTemplate is principally a category that’s designed
in line with the identical rules as the numerous different Spring Template
lessons like JdbcTemplate and JmsTemplate. It would present you a really
simplified method together with some default behaviors that can be utilized
for performing advanced duties. 

The RestTemplate class is definitely a
synchronous shopper that’s designed to name REST providers. Subsequently,
its major strategies are additionally intently associated to REST’s underpinnings.
You’ll finally get used to the HTTP protocol strategies like HEAD,
GET, DELETE, PUT, POST, and OPTIONS. 

1. Constructing RestTemplate utilizing RestTemplateBuilder

It
is feasible to construct a RestTemplate bean utilizing a wide range of strategies.
Have a look at the instance given under to see how you should use
RestTemplateBuilder.

public RestTemplate restTemplate(RestTemplateBuilder builder) {
 
	return builder
		.setConnectTimeout(Length.ofMillis(3000))
		.setReadTimeout(Length.ofMillis(3000))
		.construct();
}

2. Constructing RestTemplate Utilizing SimpleClientHttpRequestFactory

One other approach to construct RestTemplate is by making use of the SimpleClientHttpRequestFactory. See the next instance:

public RestTemplate restTemplate() {
	var manufacturing facility = new SimpleClientHttpRequestFactory();
	manufacturing facility.setConnectTimeout(3000);
	manufacturing facility.setReadTimeout(3000);
	return new RestTemplate(manufacturing facility);
}

3. Constructing RestTemplate Utilizing Apache HTTPClient

This
is probably the most environment friendly and fashionable approach to construct RestTemplate in Spring.
See the next instance to get a greater understanding:

@Autowired
CloseableHttpClient httpClient;
 
@Worth("${api.host.baseurl}")
personal String apiHost;
 
@Bean
public RestTemplate restTemplate() {

	RestTemplate restTemplate = new RestTemplate(clientHttpRequestFactory());
	restTemplate.setUriTemplateHandler(new DefaultUriBuilderFactory(apiHost));
	return restTemplate;
}

@Bean
@ConditionalOnMissingBean
public HttpComponentsClientHttpRequestFactory clientHttpRequestFactory() {

	HttpComponentsClientHttpRequestFactory clientHttpRequestFactory
			= new HttpComponentsClientHttpRequestFactory();
	clientHttpRequestFactory.setHttpClient(httpClient);
	return clientHttpRequestFactory;
}

4. How To Inject The RestTemplate Bean

You
can inject the RestTemplate bean by making use of the favored
@Autowired annotation. Utilizing the @Qualifier annotation, you can even
have a number of beans with totally different configurations. Have a look at the next
instance:
@Autowired
personal RestTemplate restTemplate;

5. Consuming Responses (String)

You
can fetch the API response within the type of a JSON string. You have to
to make use of ObjectMapper and parse it to the POJO after which use it within the
software. 

The getForObject() methodology could be actually helpful
if you’re seeking to get an unparsable response from the server. You
might also haven’t any management to have it fastened on the management aspect.
Subsequently, you get the response as a string and use the customized parser or
a string substitute perform.

personal ultimate String URI_USERS_ID = "/customers/{id}";

@Autowired
RestTemplate restTemplate;

//Utilizing RestTemplate

Map<String, String> params = new HashMap<String, String>();
params.put("id", "1");

//Parse the string after getting the response
String userStr = restTemplate.getForObject(URI_USERS_ID, String.class, params);

6. Consuming Responses To POJO

Look
on the following instance to see how one can fetch the API response immediately
into the area object utilizing the getForObject() methodology. 

personal ultimate String URI_USERS = "/customers";
personal ultimate String URI_USERS_ID = "/customers/{id}";

@Autowired
RestTemplate restTemplate;

//Utilizing RestTemplate

// "customers"
Person[] usersArray = restTemplate.getForObject(URI_USERS, Person[].class);

// "customers/{id}"
Map<String, String> params = new HashMap<String, String>();
params.put("id", "1");

Person consumer = restTemplate.getForObject(URI_USERS_ID, Person.class, params);

You may also use the getForEntity() methodology for performing the identical activity. 

personal ultimate String URI_USERS = "/customers";
personal ultimate String URI_USERS_ID = "/customers/{id}";

@Autowired
RestTemplate restTemplate;

//Utilizing RestTemplate

// "customers"
ResponseEntity<Person[]> responseEntity = restTemplate
    .getForEntity(URI_USERS, Person[].class);

// "customers/{id}"
Map<String, String> params = new HashMap<String, String>();
params.put("id", "1");

ResponseEntity<Person> responseEntity = restTemplate
    .getForEntity(URI_USERS_ID, Person.class, params);

6. Sending HTTP Headers

Take a look at the next instance to study how one can ship HTTP Headers with the RestTemplate in Spring:

personal ultimate String URI_USERS = "/customers";

@Autowired
RestTemplate restTemplate;

//Utilizing RestTemplate

HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
headers.set("X-COM-PERSIST", "NO");
headers.set("X-COM-LOCATION", "USA");

HttpEntity<String> entity = new HttpEntity<String>(headers);

ResponseEntity<Person[]> responseEntity = restTemplate
		.alternate(URI_USERS, HttpMethod.GET, entity, Person[].class);

7. How To Ship URL Parameters In Spring

You should use the next syntax for sending URL parameters in Spring:

Map<String, String> params = new HashMap<String, String>();
params.put("id", "1");

ResponseEntity<Person> responseEntity = restTemplate
	.getForEntity(URI_USERS_ID, Person.class, params);

8. Consuming A POST API 

You may also use the RestTemplate in Spring for accessing HTTP POST API requests. 

personal ultimate String URI_USERS = "/customers";

@Autowired
RestTemplate restTemplate;

//Utilizing RestTemplate

Person newUser = new Person(1, "Alex", "Golan", "a@mail.com");
Person createdUser = restTemplate.postForObject(URI_USERS, newUser, Person.class);
//Use the thing as wanted

9. How To Eat A PUT API

personal ultimate String URI_USERS_ID = "/customers/{id}";

@Autowired
RestTemplate restTemplate;

//Utilizing RestTemplate

Map<String, String> params = new HashMap<String, String>();
params.put("id", "2");

Person updatedUser = new Person(1, "Alex", "Golan", "a@mail.com");
Person consumer = restTemplate.put(URI_USERS_ID, updatedUser, Person.class);
//Use the thing as wanted


10. How To Eat A DELETE API

personal ultimate String URI_USERS_ID = "/customers/{id}";

@Autowired
RestTemplate restTemplate;

Map<String, String> params = new HashMap<String, String>();
params.put("id", "2");

//Utilizing RestTemplate

restTemplate.delete ( URI_USERS_ID,  params );

RestTemplate Steadily Requested Questions

1. What precisely is RestTemplate?

In
Spring, the RestTemplate is principally a category that’s designed
in line with the identical rules as the numerous different Spring Template
lessons like JdbcTemplate and JmsTemplate. It would present you a really
simplified method together with some default behaviors that can be utilized
for performing advanced duties

2. What can I do with the RestTemplate?

The
RestTemplate class is definitely a synchronous shopper that’s designed to
name REST providers. Subsequently, its major strategies are additionally intently
associated to REST’s underpinnings. You’ll finally get used to the
HTTP protocol strategies like HEAD, GET, DELETE, PUT, POST, and OPTIONS. 

3. Is it doable to Autowire RestTemplate?

You can not autowire the RestTemplate with out specifying the actual bean configuration. 

Conclusion

As
you possibly can see, you should use the examples given on this checklist to grasp
the basics of the RestTemplate in Spring. If you happen to appreciated this checklist
of 10 examples of the RestTemplate in Spring, be happy to share it with
your family and friends.

 

Different Java REST Tutorials and Assets it’s possible you’ll like

  • 7 Finest Programs to study Spring Framework (finest programs)
  • Methods to create a REST shopper utilizing the Spring framework in Java? (tutorial)
  • High 5 Books to study RESTful APIs and Internet Companies (books)
  • 10 Free Programs to study Spring Boot (Free Programs)
  • My Favourite Programs to study Software program Structure (programs)
  • Spring HelloWorld Instance utilizing Dependency Injection (tutorial)
  • Methods to convert a JSON array to a String array in Java? (tutorial)
  • High 5 programs to study GraphQL for Inexperienced persons (programs)
  • High 10 REST Internet Service Interview Questions (reply)
  • High 5 Programs to study RESTFul Internet Companies in Java? (programs)
  • Distinction between Idempotent and secure strategies in HTTP? (reply)
  • Distinction between REST and SOAP Internet Companies? (reply)
  • Methods to create a JDBC connection pool utilizing Spring? (tutorial)
  • Distinction between PUT vs POST in REST Internet Service? (article)
  • High 10 Programs to study Microservices for Java builders (programs)

Thanks for studying this text up to now. If you happen to like this tutorial of
sending HTTP requests from the Java Program utilizing RestTemplate then please share them with
your pals and colleagues. You probably have any questions or suggestions then
please drop a observe.

You may also put up a remark if you happen to
have any doubts about any of the examples given on this checklist and we are going to
get again to you as quickly as doable. 

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments