使用Apache HttpClient下载文件的步骤如下:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
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)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
inputStream.close();
}
response.close();
httpClient.close();
这样就完成了使用Apache HttpClient下载文件的操作。