一、什么是RestTemplate
RestTemplate 是 Spring 框架提供的一个用于访问 REST 服务的组件,底层对 HTTP 请求及响应进行了封装,提供了很多访问远程REST服务的方法,可简化代码开发。
二、实例化RestTemplate
@Configuration
@ComponentScan(basePackageClasses = RecordingConfig.class)
public class RecordingConfig {
/**
* 支持重定向的restTemplate
*
* @return
*/
@Bean
public RestTemplate restTemplate() {
final RestTemplate restTemplate = new RestTemplate();
final HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
final HttpClient httpClient = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy()).build();
factory.setHttpClient(httpClient);
restTemplate.setRequestFactory(factory);
return restTemplate;
}
}
三、下载远程文件到本地
@Service
public class Test extends BaseService {
@Autowired
private RestTemplate restTemplate;
public void download(String remoteUrl, String localUrl) {
File localFile = new File(localUrl);
if (!localFile.getParentFile().exists()) {
localFile.getParentFile().mkdirs();
}
int reTry = 1;
while (true) {
ResponseEntity<File> responseEntity = restTemplate.execute(remoteUrl, HttpMethod.GET, null, response -> {
if (response.getStatusCode() == HttpStatus.OK) {
FileCopyUtils.copy(response.getBody(), new FileOutputStream(localFile));
return ResponseEntity.status(response.getStatusCode()).headers(response.getHeaders()).body(localFile);
} else {
return null;
}
});
if (responseEntity != null && responseEntity.getStatusCode() == HttpStatus.OK) {
break;
}
reTry++;
if (reTry >= 3) {
logger.error("下载远程文件失败!remoteUrl: {}", remoteUrl);
break;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
}
}
}
四、测试下载