> For the complete documentation index, see [llms.txt](https://jack80342.gitbook.io/spring-boot/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://jack80342.gitbook.io/spring-boot/iv.-spring-boot-features/33.-calling-rest-services-with-resttemplate.md).

# 33. 使用RestTemplate调用REST服务

如果应用需要调用远程REST服务，你可以使用Spring框架的`RestTemplate`类。由于`RestTemplate`实例经常在使用前需要自定义，Spring Boot就没有提供任何自动配置的`RestTemplate` bean。不过，你可以通过自动配置的`RestTemplateBuilder`创建自己需要的`RestTemplate`实例。自动配置的`RestTemplateBuilder`会确保应用到`RestTemplate`实例的`HttpMessageConverters`是合适的。

以下是典型的示例：

```java
@Service
public class MyService {

    private final RestTemplate restTemplate;

    public MyBean(RestTemplateBuilder restTemplateBuilder) {
        this.restTemplate = restTemplateBuilder.build();
    }

    public Details someRestCall(String name) {
        return this.restTemplate.getForObject("/{name}/details", Details.class, name);
    }

}
```

**注** `RestTemplateBuilder`包含很多有用的方法，可以用于快速配置一个`RestTemplate`。例如，你可以使用`builder.basicAuthorization("user", "password").build()`添加基本的认证支持（BASIC auth）。


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://jack80342.gitbook.io/spring-boot/iv.-spring-boot-features/33.-calling-rest-services-with-resttemplate.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
