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或其子类(如HttpClientErrorExceptionHttpServerErrorException)来处理请求失败的情况。


6. 注意事项

  • 线程安全性RestTemplate是线程安全的,可以作为单例Bean使用。

  • 性能优化:在高并发场景下,RestTemplate的性能可能不如WebClient(Spring 5引入的响应式客户端)。如果需要更好的性能,可以考虑使用WebClient

  • 日志记录:通过拦截器或日志框架记录请求和响应信息,方便调试和排查问题。

posted @   软件职业规划  阅读(72)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示