前面有写过HttpPost上传文件,结果不久又遇到要用java代码去下载文件的需求;代码中的url是文件的访问地址
public static byte[] get(String url, Map<String, String> headers) throws ClientProtocolException, IOException {
logger.info("Ready Get Request Url[{}]", url);
HttpGet get = new HttpGet(url);
setHttpHeaders(get, headers);
HttpResponse response = HttpClients.createDefault().execute(get);
if (null == response || response.getStatusLine() == null) {
logger.info("Post Request For Url[{}] is not ok. Response is null", url);
return null;
} else if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
logger.info("Post Request For Url[{}] is not ok. Response Status Code is {}", url,
response.getStatusLine().getStatusCode());
return null;
}
return EntityUtils.toByteArray(response.getEntity());
}