普通的方式不能下载大文件,会oom,要下载大文件建议使用流式处理下载
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.ByteArrayHttpMessageConverter;
import org.springframework.web.client.RestTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.http.HttpHeaders;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
public class FileDownloader {
public static void downloadFile(String fileUrl, String localFilePath) {
RestTemplate restTemplate = new RestTemplate();
// 添加一个能处理video/mp4类型响应的HttpMessageConverter
restTemplate.getMessageConverters().add(new ByteArrayHttpMessageConverter());
ResponseEntity<byte[]> response = restTemplate.getForEntity(fileUrl, byte[].class);
if (response.getStatusCode().is2xxSuccessful()) {
HttpHeaders headers = response.getHeaders();
try (InputStream in = new ByteArrayInputStream(response.getBody());
FileOutputStream out = new FileOutputStream(localFilePath)) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
}
System.out.println("File downloaded successfully to: " + localFilePath);
} catch (IOException e) {
System.err.println("Error downloading file: " + e.getMessage());
}
} else {
System.err.println("Error downloading file. HTTP status code: " + response.getStatusCodeValue());
}
}
public static void main(String[] args) {
String fileUrl = "http://example.com/file-to-download.mp4";
String localFilePath = "/path/to/save/file.mp4";
downloadFile(fileUrl, localFilePath);
}
}