33. Calling REST services

If you need to call remote REST services from your application, you can use Spring
Framework’s RestTemplate class. Since RestTemplate instances often need to be
customized before being used, Spring Boot does not provide any single auto-configured
RestTemplate bean. It does, however, auto-configure a RestTemplateBuilder which can be
used to create RestTemplate instances when needed. The auto-configured
RestTemplateBuilder will ensure that sensible HttpMessageConverters are applied
to RestTemplate instances.

RestTemplateBuilder includes a number of useful methods that can be used to quickly
configure a RestTemplate. For example, to add BASIC auth support you can use
builder.basicAuthorization("user", "password").build().

33.1 RestTemplate customization

There are three main approaches to RestTemplate customization, depending on how broadly
you want the customizations to apply.

To make the scope of any customizations as narrow as possible, inject the auto-configured
RestTemplateBuilder and then call its methods as required. Each method call returns a
new RestTemplateBuilder instance so the customizations will only affect this use of
the builder.

To make an application-wide, additive customization a RestTemplateCustomizer bean can be
used. All such beans are automatically registered with the auto-configured
RestTemplateBuilder and will be applied to any templates that are built with it.

Here’s an example of a customizer that configures the use of a proxy for all hosts except
192.168.0.5:

Lastly, the most extreme (and rarely used) option is to create your own
RestTemplateBuilder bean. This will switch off the auto-configuration of a
RestTemplateBuilder and will prevent any RestTemplateCustomizer beans from being used.