使用Apache HttpClient下载文件
使用Apache HttpClient下载文件的步骤以下:
org.apache.httpcomponents
httpclient
4.5.13
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(url);
CloseableHttpResponse response = httpClient.execute(httpGet);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
// 文件下载逻辑
} else {
// 要求失败逻辑
}
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream inputStream = entity.getContent();
FileOutputStream outputStream = new FileOutputStream("output-file-path");
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != ⑴) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
inputStream.close();
}
response.close();
httpClient.close();
这样就完成了使用Apache HttpClient下载文件的操作。
TOP