阅读量:7
使用Apache HttpClient下载文件的步骤如下:
- 首先,导入Apache HttpClient的依赖包。如果使用Maven管理项目依赖,可以在pom.xml文件中添加以下依赖:
<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.13</version> </dependency>
- 创建一个HttpClient对象:
CloseableHttpClient httpClient = HttpClients.createDefault();
- 创建HttpGet请求,并设置请求的URL:
HttpGet httpGet = new HttpGet(url);
- 发送请求并获取响应:
CloseableHttpResponse response = httpClient.execute(httpGet);
- 检查响应的状态码,如果状态码为200表示请求成功:
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(); }
- 最后,记得关闭HttpClient和HttpResponse对象:
response.close(); httpClient.close();
这样就完成了使用Apache HttpClient下载文件的操作。