springboot 之 使用RestTemplate发起http请求

本文详细介绍如何在SpringBoot项目中使用RestTemplate调用第三方HTTP接口。从配置RestTemplate开始,到封装请求工具类,最后演示实际调用过程,帮助开发者快速掌握技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前言: 在我们用springboot 开发项目的过程用,会有调用第三方http接口的情况,这时我们使用spring的RestTemplate,使用更方便。

1,我们可以自己看下RestTemplate源码,提供了好多请求格式,你可以自己选择使用。具体方法说明网上都有,常用的getForEntity,getForObject,postForObject,postForEntity,exchange

2,如何在springboot中使用:

   第一步:写配置加载类 RestTemplateConfig.java 

   直接上代码

import com.newcapec.shuttlebus.utils.HttpRequestUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.ResponseErrorHandler;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.nio.charset.Charset;
@Configuration
public class RestTemplateConfig {
    @Bean
    public RestTemplate restTemplate(ClientHttpRequestFactory factory) {
        RestTemplate restTemplate = new RestTemplate(factory);
        restTemplate.getMessageConverters().set(1,
                new StringHttpMessageConverter(Charset.forName("UTF-8")));
        restTemplate.setErrorHandler(new ThrowErrorHandler());
        return restTemplate;
    }

    @Bean
    public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        factory.setReadTimeout(10000);//单位为ms
        factory.setConnectTimeout(5000);//单位为ms
        return factory;
    }

    /**
     * 注入封装RestTemplate
     * @Title: httpRequestUtils
     * @return httpRequestUtils
     */
    @Bean(name = "httpRequestUtils")
    public HttpRequestUtils httpRequestUtils(RestTemplate restTemplate) {
        HttpRequestUtils httpRequestUtils = new HttpRequestUtils();
        httpRequestUtils.setRestTemplate(restTemplate);
        return httpRequestUtils;
    }
    class ThrowErrorHandler implements ResponseErrorHandler {
        @Override
        public boolean hasError(ClientHttpResponse response) throws IOException {
            //返回false表示不管response的status是多少都返回没有错
            //这里可以自己定义那些status code你认为是可以抛Error
            return false;
        }
        @Override
        public void handleError(ClientHttpResponse response) throws IOException {
            System.out.println("================>" + response.getBody());
            //这里面可以实现你自己遇到了Error进行合理的处理
        }
    }

}

第二步:第一步中 我这里将restTemplate封装到了一个工具类里httpRequestUtils并注入到spring工厂里 ,下边把这个工具http请求的工具类发出来:

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.*;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
public class HttpRequestUtils {
    protected static final transient Logger LOGGER = LoggerFactory.getLogger(HttpRequestUtils.class);
    private RestTemplate restTemplate;
    public void setRestTemplate(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }
    public String sendHttpRequestForm(String url, MultiValueMap<String, String> params) throws IOException {
        LOGGER.debug("sendHttpRequestForm:{}", params.toString()); // 打印结果页面
        HttpHeaders headers = new HttpHeaders();
        // 提交方式表单提交
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<MultiValueMap<String, String>>(params, headers);
        //  执行HTTP请求
        try{
            ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);
            if(response.getStatusCode().isError()){
                return "error";
            }
            return response.getBody();
        }catch (Exception e){
            e.printStackTrace();
        }
        return "error";
    }

}

第三步:使用,上代码

    // 加载
    @Autowired
    private HttpRequestUtils httpRequestUtils;
// 调用
String result = httpRequestUtils.sendHttpRequestForm(serviceURL, maps);

 注意:maps这个参数是 MultiValueMap 类型的,serviceURL是请求的http地址

3,开发完成,可以测试了。

<think>嗯,用户问的是如何用Spring Boot的RestTemplate通过HTTP请求下载文件到本地。我得先回忆一下RestTemplate的基本用法,特别是处理文件下载的部分。首先,RestTemplate是用来发送HTTP请求的,比如GET、POST等。对于文件下载,通常是用GET方法获取文件流,然后保存到本地。 用户可能已经知道RestTemplate的基本配置,但需要具体的下载步骤。可能需要提到如何发起请求,获取响应体,处理输入流,保存到文件。要注意的是,RestTemplate默认的MessageConverter可能不支持文件下载,或者需要正确配置。比如,可能需要使用ByteArrayHttpMessageConverter来正确处理字节数组,这样响应才能被正确解析为byte[]。 然后,具体的步骤应该包括:创建RestTemplate实例,发送GET请求,获取响应体的字节数组,再用FileOutputStream将字节写入到本地文件。同时,要处理可能的异常,比如资源未找到(404错误),这时候可以用try-catch块来捕获HttpClientErrorException,并给出提示。 另外,可能需要提到文件名的问题。如果服务器返回的响应头里有文件名信息,比如Content-Disposition,可以解析出来作为保存的文件名。不过用户的问题里没有提到这个,所以可能暂时不需要处理,或者简单说明一下。 还要注意关闭资源,比如输入流和输出流,避免资源泄漏。不过使用try-with-resources的话,可以自动关闭,这在Java 7及以上是可行的。示例代码可能需要考虑到这一点,或者至少在finally块中关闭流。 可能的错误点包括没有正确处理响应类型,导致获取不到字节数组,或者保存文件时路径错误。需要提醒用户检查URL是否正确,是否有写入权限等。 最后,提供一个完整的示例代码,展示如何从创建RestTemplate到保存文件的全过程,并解释每个步骤的作用。这样用户可以直接参考代码实现,并根据自己的需求调整。</think>在Spring Boot中使用RestTemplate下载文件到本地的步骤如下: ### 一、核心原理 通过RestTemplate发送HTTP GET请求获取文件流,使用Java I/O流将响应内容写入本地文件系统。 ### 二、实现步骤 #### 1. 创建RestTemplate实例 ```java RestTemplate restTemplate = new RestTemplate(); ``` #### 2. 发送HTTP请求 ```java // 设置请求头(可选) HttpHeaders headers = new HttpHeaders(); headers.set("Authorization", "Bearer your_token"); // 创建请求实体 HttpEntity<String> requestEntity = new HttpEntity<>(headers); // 发送请求并接收字节数组响应 ResponseEntity<byte[]> response = restTemplate.exchange( "http://example.com/file.pdf", HttpMethod.GET, requestEntity, byte[].class ); ``` #### 3. 验证响应状态 ```java if (response.getStatusCode() == HttpStatus.OK && response.hasBody()) { // 处理响应内容 } else { throw new RuntimeException("文件下载失败"); } ``` #### 4. 保存文件到本地 ```java try (FileOutputStream fos = new FileOutputStream("local_file.pdf")) { byte[] fileContent = response.getBody(); fos.write(fileContent); } catch (IOException e) { throw new RuntimeException("文件写入失败", e); } ``` ### 三、完整示例代码 ```java public void downloadFile(String url, String localPath) { try { RestTemplate restTemplate = new RestTemplate(); // 添加支持字节数组的转换器 restTemplate.getMessageConverters().add(new ByteArrayHttpMessageConverter()); ResponseEntity<byte[]> response = restTemplate.getForEntity( url, byte[].class ); if (response.getStatusCode() == HttpStatus.OK && response.hasBody()) { try (FileOutputStream fos = new FileOutputStream(localPath)) { fos.write(response.getBody()); System.out.println("文件下载成功:" + localPath); } } } catch (HttpClientErrorException e) { System.err.println("服务器响应错误:" + e.getStatusCode()); } catch (IOException e) { System.err.println("文件保存失败:" + e.getMessage()); } } ``` ### 四、注意事项 1. **大文件处理**:对于大文件建议使用流式处理 ```java InputStream inputStream = restTemplate.execute( url, HttpMethod.GET, null, response -> response.getBody() ); ``` 2. **文件名获取**:建议从响应头解析 ```java String fileName = response.getHeaders() .getContentDisposition() .getFilename(); ``` 3. **异常处理**:需处理以下异常 - HttpClientErrorException:4xx错误 - HttpServerErrorException:5xx错误 - ResourceAccessException:连接超时 4. **性能优化**:建议配置连接池 ```java HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(); factory.setConnectTimeout(5000); RestTemplate restTemplate = new RestTemplate(factory); ``` ### 五、推荐实践 1. 使用`RestTemplateBuilder`创建实例 2. 添加MD5校验保证文件完整性 3. 使用NIO的`Files.copy()`替代传统IO流 4. 配置重试机制(Spring Retry) 通过以上步骤,即可实现使用RestTemplate进行文件下载。实际开发中建议根据业务需求添加日志记录、进度监控等功能。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值