Spring Boot集成RestTemplate:实现HTTP请求调用
1. 添加依赖
在Spring Boot项目中,RestTemplate
已经包含在spring-boot-starter-web
依赖中。如果你的项目已经引入了该依赖,则无需额外添加。如果没有,可以在pom.xml
文件中添加以下依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
2. 配置RestTemplate
Bean
在Spring Boot中,RestTemplate
需要通过Bean的方式进行配置。你可以在配置类中定义一个RestTemplate
Bean,这样Spring容器会自动管理它的生命周期。
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
@Configuration
public class AppConfig {
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
3. 使用RestTemplate
发起请求
在你的服务类或控制器中,注入RestTemplate
并使用它来发起HTTP请求。以下是几种常见的请求方式:
示例:调用GET请求
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
@RestController
public class MyController {
@Autowired
private RestTemplate restTemplate;
@GetMapping("/call-api")
public String callExternalApi() {
// 调用外部API
String url = "https://api.example.com/data";
String response = restTemplate.getForObject(url, String.class);
return response;
}
}
示例:调用POST请求
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
@RestController
public class MyController {
@Autowired
private RestTemplate restTemplate;
@GetMapping("/call-api")
public String callExternalApi() {
// 调用外部API
String url = "https://api.example.com/data";
MyRequest request = new MyRequest();
request.setName("Kimi");
request.setAge(25);
MyResponse response = restTemplate.postForObject(url, request, MyResponse.class);
return response.toString();
}
}
4. 配置拦截器(可选)
如果需要对RestTemplate
的请求进行拦截(例如添加统一的请求头、日志记录等),可以配置拦截器。
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.web.client.RestTemplate;
import java.util.Collections;
@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate() {
RestTemplate restTemplate = new RestTemplate();
restTemplate.setInterceptors(Collections.singletonList((request, body, execution) -> {
request.getHeaders().add("Authorization", "Bearer your-token");
return execution.execute(request, body);
}));
return restTemplate;
}
}
5. 使用RestTemplate
的高级功能
RestTemplate
还支持更高级的用法,例如:
-
使用
ResponseEntity
获取完整的响应信息:ResponseEntity<MyResponse> responseEntity = restTemplate.getForEntity(url, MyResponse.class);
-
处理异常:通过捕获
RestClientException
或其子类(如HttpClientErrorException
、HttpServerErrorException
)来处理请求失败的情况。
6. 注意事项
-
线程安全性:
RestTemplate
是线程安全的,可以作为单例Bean使用。 -
性能优化:在高并发场景下,
RestTemplate
的性能可能不如WebClient
(Spring 5引入的响应式客户端)。如果需要更好的性能,可以考虑使用WebClient
。 -
日志记录:通过拦截器或日志框架记录请求和响应信息,方便调试和排查问题。
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步