• SpringBoot_RestTemplate使用总结


    介绍

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

    springboot使用

    1.maven依赖

            <dependency>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-starter-webartifactId>
            dependency>
    
    • 1
    • 2
    • 3
    • 4

    2.简单使用

    2.1 RestTemplate配置

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

    @Configuration
    public class RestTemplateConfig {
    
        @Bean
        public RestTemplate restTemplate(RestTemplateBuilder builder) {
            return builder.build();
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    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);
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    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);
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    更复杂场景

    
    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;
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22

    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;
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    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;
            }
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45

    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);
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30

    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);
            }
        }
    }
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33

    附录

  • 相关阅读:
    POJ3275 Ranking the Cows题解
    stream之map的用法
    微信小程序 |从零实现酷炫纸质翻页效果
    【Scan kit】Sechunter针对统一扫码SDK扫出漏洞该如何解决?
    轻松掌握组件启动之MongoDB(上):高可用复制集架构环境搭建
    web 前端 JavaScript 内置对象
    [附源码]java毕业设计8号体育用品销售及转卖系统
    Android 9 固定以太网MAC地址(cmdline)
    爱心html制作并部署github
    专访通过 OBCP V3 首位考生:V3 让知识更加结构化、体系化
  • 原文地址:https://blog.csdn.net/Myron_007/article/details/133747509