resttemplate获取文件
时间: 2025-03-12 22:08:44 浏览: 33
### 使用Spring RestTemplate从服务器下载或接收文件
为了使用 `RestTemplate` 下载或接收文件,通常会涉及到二进制数据的传输。下面介绍一种最佳实践方法以及相应的示例代码。
#### 创建配置类设置超时和其他必要的属性
由于文件操作可能会比较耗时,因此建议先定义一个配置类来调整连接时间和读取时间等参数[^1]:
```java
import org.apache.http.impl.client.HttpClients;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate(ClientHttpRequestFactory factory){
return new RestTemplate(factory);
}
@Bean
public ClientHttpRequestFactory simpleClientHttpRequestFactory(){
HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
factory.setConnectTimeout(5000); // 单位为毫秒
factory.setReadTimeout(5000); // 单位为毫秒
return factory;
}
}
```
#### 编写服务层逻辑执行实际的文件下载任务
接下来,在具体的服务实现中可以这样编写代码来进行文件下载[^2][^3]:
```java
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.ResponseEntity;
import java.nio.file.Path;
import java.nio.file.Paths;
@Service
public class FileDownloadService {
private final RestTemplate restTemplate;
public FileDownloadService(RestTemplateBuilder restTemplateBuilder) {
this.restTemplate = restTemplateBuilder.build();
}
/**
* 文件下载接口.
*/
public Resource downloadFile(String fileUrl, Path targetPath) throws Exception{
ResponseEntity<byte[]> response =
restTemplate.getForEntity(fileUrl, byte[].class);
if (!response.getStatusCode().is2xxSuccessful()){
throw new RuntimeException("Failed to fetch the resource");
}
Files.write(targetPath, Objects.requireNonNull(response.getBody()));
return new FileSystemResource(targetPath.toFile());
}
}
```
这段代码展示了如何利用 `RestTemplate` 向指定 URL 发起 GET 请求,并将返回的数据保存到本地磁盘上作为文件资源对象返回给调用者。
#### 处理多部分表单数据(如果涉及)
如果有额外的需求比如同时上传普通参数和文件,则还需要引入一些辅助库如 commons-io 来帮助完成 multipart/form-data 类型的内容解析工作。
```xml
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.8.0</version>
<scope>compile</scope>
</dependency>
```
以上就是关于如何使用 Spring 的 `RestTemplate` 实现文件下载的一些指导信息和技术细节。
阅读全文
相关推荐


















