使用RestTemplate获得网络图片

RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
HttpEntity<String> emEntity = new HttpEntity<String>(headers);
String url = "文件的网络地址";
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
try {
ResponseEntity<byte[]> response = restTemplate.exchange(builder.build().toUri(), HttpMethod.GET,emEntity,byte[].class);
if(null!=response.getBody()) {
// 文件的格式可以由url获取
File file = new File("/xxx/xxx/xxx.xxx");
OutputStream output = new FileOutputStream(file);
BufferedOutputStream bufferedOutput = new BufferedOutputStream(output);
bufferedOutput.write(response.getBody());
bufferedOutput.close();
}
 
} catch (FileNotFoundException e) {
logger.info("错误1");
} catch (IOException e) {
logger.info("错误2");
} catch (Exception e) {
logger.info("错误3");
}

爆款云服务器s6 2核4G 低至0.46/天,具体规则查看活动详情Blog Img