Java 通过URL进行远程文件下载

@Service
public class FileService {
private static Logger LOGGER = LoggerFactory.getLogger(FileService.class);

@Autowired
private HttpService httpService;
@Autowired
private CloseableHttpClient httpClient;
@Autowired
private RequestConfig config;

public ByteArrayInputStream download2(String url) {
CloseableHttpResponse response = null;
try {
url = url.replaceAll(" ", "%20");
LOGGER.info("download fileUrl:{}",url);
URIBuilder builder = new URIBuilder(url);
builder.setParameter("code", genGoogleCode());
HttpGet httpGet = new HttpGet(builder.build());
httpGet.setConfig(config);
response = this.httpClient.execute(httpGet);
} catch (Exception e) {
LOGGER.error("文件下载失败 {}", e);
throw new MultipartException("文件下载失败");
}
try (InputStream inputStream = response.getEntity().getContent()) {
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(IOUtils.toByteArray(inputStream));
return byteArrayInputStream;
} catch (Exception e) {
LOGGER.error("文件服务器获取Outputstream 错误!{}", e);
throw new MultipartException("文件服务器获取Output Stream 错误");
}
}
}

 

posted @ 2020-09-01 15:05  曹丽是我女朋友。  阅读(2096)  评论(0编辑  收藏  举报