restTemplate 文件下载
时间: 2023-11-19 21:46:58 浏览: 125
你可以使用 Spring Framework 中的 RestTemplate 来实现文件下载功能。下面是一个简单的示例:
```java
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.client.RequestCallback;
import org.springframework.web.client.ResponseExtractor;
import org.springframework.web.client.RestTemplate;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
public class FileDownloader {
public static void downloadFile(String url, String savePath) throws IOException {
RestTemplate restTemplate = new RestTemplate();
RequestCallback requestCallback = request -> request.getHeaders()
.setAccept(MediaType.APPLICATION_OCTET_STREAM);
ResponseExtractor<ResponseEntity<byte[]>> responseExtractor = restTemplate.responseEntityExtractor(byte[].class);
ResponseEntity<byte[]> responseEntity = restTemplate.execute(url, HttpMethod.GET, requestCallback, responseExtractor);
if (responseEntity.getStatusCode().is2xxSuccessful()) {
HttpHeaders headers = responseEntity.getHeaders();
String fileName = getFileNameFromHeaders(headers);
if (fileName != null) {
savePath = savePath + File.separator + fileName;
}
byte[] fileData = responseEntity.getBody();
if (fileData != null) {
try (FileOutputStream fos = new FileOutputStream(savePath)) {
fos.write(fileData);
fos.flush();
}
}
}
}
private static String getFileNameFromHeaders(HttpHeaders headers) {
String[] contentDispositionHeader = headers.getFirst(HttpHeaders.CONTENT_DISPOSITION).split(";");
for (String name : contentDispositionHeader) {
if ((name.trim().startsWith("filename"))) {
String[] tmp = name.split("=");
return tmp[1].trim().replaceAll("\"", "");
}
}
return null;
}
}
```
你可以使用 `downloadFile` 方法来下载文件。传入文件的 URL 和保存路径即可。例如:
```java
String url = "http://example.com/files/myfile.pdf";
String savePath = "/path/to/save/file";
FileDownloader.downloadFile(url, savePath);
```
这将会将指定 URL 的文件下载到指定的保存路径中。确保在使用前添加相应的依赖,如 Spring Web 客户端依赖:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
```
希望对你有所帮助!如果有任何疑问,请随时提问。
阅读全文