一、什麼是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) {
}
}
}
}
四、測試下載