SpringBoot_RestTemplate使用总结

RestTemplate使用总结

  • 介绍
  • springboot使用
    • 1.maven依赖
    • 2.简单使用
      • 2.1 RestTemplate配置
      • 2.2 Get请求
      • 2.3 Post请求
    • 3.进阶使用
      • 3.1 全局超时配置
      • 3.2 请求及响应日志
      • 3.3 文件上传
      • 3.4 文件下载
  • 附录

介绍

RestTemplate是一个用于访问REST服务的Spring框架的模板工具类。它提供了一种方便的方式来与RESTful服务进行通信

springboot使用

1.maven依赖

        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>

2.简单使用

2.1 RestTemplate配置

因为http请求的模板工具类,springboot默认没有自动装配, 直接RestTemplate restTemplate = new RestTemplate();就可以, 不过一般项目中都配置成单例

@Configuration
public class RestTemplateConfig {

    @Bean
    public RestTemplate restTemplate(RestTemplateBuilder builder) {
        return builder.build();
    }
}

2.2 Get请求

public class MyService {
    private final String API_URL = "https://api.example.com/data";

    private final RestTemplate restTemplate;

    public MyService(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    public String fetchData() {
        return restTemplate.getForObject(API_URL, String.class);
    }
}

2.3 Post请求

public class MyService {
    private final String API_URL = "https://api.example.com/data";

    private final RestTemplate restTemplate;

    public MyService(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    public void postData(String data) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        HttpEntity<String> requestEntity = new HttpEntity<>(data, headers);

        restTemplate.postForObject(API_URL, requestEntity, String.class);
    }
}

更复杂场景


public class MyService {
    private final String API_URL = "https://api.example.com/data";

    private final RestTemplate restTemplate;

    public MyService(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    public ResponseEntity<String> fetchDataWithHeaders() {
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", "Bearer YOUR_ACCESS_TOKEN");

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

        ResponseEntity<String> response = restTemplate.exchange(API_URL, HttpMethod.GET, entity, String.class);

        return response;
    }
}

3.进阶使用

3.1 全局超时配置


@Configuration
public class RestTemplateConfig {

    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate(clientHttpRequestFactory());
    }

    private ClientHttpRequestFactory clientHttpRequestFactory() {
        int timeout = 5000; // 超时时间,单位为毫秒
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        factory.setConnectTimeout(timeout);
        factory.setReadTimeout(timeout);
        return factory;
    }
}

3.2 请求及响应日志

默认RestTemplate不打印日志,因此我们可以用拦截器实现CustomRequestResponseLoggingInterceptor

@Configuration
public class RestTemplateConfig {

    @Bean
    public RestTemplate restTemplate() {
        // 设置ClientHttpRequestFactory为BufferingClientHttpRequestFactory
        ClientHttpRequestFactory factory = new BufferingClientHttpRequestFactory(new SimpleClientHttpRequestFactory());

        // 创建RestTemplate实例
        RestTemplate restTemplate = new RestTemplate(factory);

        // 添加自定义的ClientHttpRequestInterceptor用于记录请求和响应日志
        restTemplate.setInterceptors(Collections.singletonList(new CustomRequestResponseLoggingInterceptor()));

        return restTemplate;
    }

    private static class CustomRequestResponseLoggingInterceptor implements ClientHttpRequestInterceptor {
        @Override
        public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
            // 打印请求日志
            System.out.println("Request: " + request.getMethod() + " " + request.getURI());
            // 打印请求头
            System.out.println("Request Headers: " + request.getHeaders());
            // 打印请求body(如果有的话)
            if (body.length > 0) {
                System.out.println("Request Body: " + new String(body, Charset.defaultCharset()));
            }

            // 执行请求
            ClientHttpResponse response = execution.execute(request, body);

            // 打印响应日志
            System.out.println("Response Status Code: " + response.getStatusCode());
            // 打印响应body(如果有的话)
            String responseBody = StreamUtils.copyToString(response.getBody(), Charset.defaultCharset());
            if (!responseBody.isEmpty()) {
                System.out.println("Response Body: " + responseBody);
            }

            return response;
        }
    }
}

3.3 文件上传

public class FileService {

    private final RestTemplate restTemplate;

    public FileService(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    public void uploadFile(String apiUrl, File file) {
        MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
        body.add("file", new FileSystemResource(file));

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);

        restTemplate.exchange(apiUrl, HttpMethod.POST, new RequestCallback() {
            @Override
            public void doWithRequest(org.springframework.http.client.ClientHttpRequest request) {
                request.getHeaders().addAll(headers);
            }
        }, new ResponseExtractor<ResponseEntity<String>>() {
            @Override
            public ResponseEntity<String> extractData(org.springframework.http.client.ClientHttpResponse response) {
                // Handle response if needed
                return null;
            }
        }, body);
    }
}

3.4 文件下载

public class FileService {

    private final RestTemplate restTemplate;

    public FileService(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    public void downloadFile(String apiUrl, String savePath) throws IOException {
        ResponseEntity<Resource> responseEntity = restTemplate.exchange(apiUrl, HttpMethod.GET, new RequestCallback() {
            @Override
            public void doWithRequest(org.springframework.http.client.ClientHttpRequest request) {
                // Set headers if needed
            }
        }, Resource.class);

        Resource resource = responseEntity.getBody();
        if (resource != null) {
            Path filePath = Path.of(savePath);
            Path parentDir = filePath.getParent();

            // 创建父目录
            if (parentDir != null && !Files.exists(parentDir)) {
                Files.createDirectories(parentDir);
            }

            // 保存文件
            Files.copy(resource.getInputStream(), filePath, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
        }
    }
}


附录

你可能感兴趣的:(springboot,spring,boot,后端,java)