[Java] 使用HttpClient实现文件下载
时间: 2023-12-26 12:05:43 浏览: 83
好的,关于使用HttpClient实现文件下载,您需要先创建一个HttpClient对象,然后构建一个HttpGet请求,并设置请求头等相关参数,最后将请求发送给服务器并获取服务器响应,将响应流保存到本地文件即可。具体操作可以参考下面的Java代码示例:
```
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet("https://www.example.com/file.zip");
HttpResponse response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream inputStream = entity.getContent();
FileOutputStream fileOutputStream = new FileOutputStream("file.zip");
byte[] buffer = new byte[1024];
int len;
while ((len = inputStream.read(buffer)) > 0) {
fileOutputStream.write(buffer, 0, len);
}
fileOutputStream.close();
inputStream.close();
}
```
以上代码片段仅供参考,具体实现需要根据实际情况进行调整。
阅读全文