下面是使用HttpClient实现文件下载的完整攻略,我将详细讲解该过程并提供两个示例说明。
简介
HttpClient是Apache软件基金会下的一个开源HTTP客户端库,它支持Http/Https协议,并具有稳定、高效、易用的特点。本文将介绍如何使用HttpClient来实现文件下载。
下载依赖
我们需要在项目中引入HttpClient的依赖,该依赖在Maven仓库中的名称为“httpclient",需要注意的是,如果是使用HttpClient版本大于4.3.x,还需要引入另一个依赖“httpcore”,如下所示:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.6</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.11</version>
</dependency>
实现文件下载
使用HttpClient实现文件下载的主要步骤如下:
-
创建HttpClient实例。
-
创建HttpGet实例,并设置下载文件的URL地址。
-
执行HttpGet请求,获取文件内容,并将内容写入到文件中。
-
关闭HttpClient连接。
具体实现方式如下所示:
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class FileDownloader {
private static final String FILE_URL = "https://example.com/file.zip";
private static final String FILE_NAME = "file.zip";
public static void main(String[] args) {
ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);
executorService.scheduleAtFixedRate(() -> {
try {
downloadFile(FILE_URL, FILE_NAME);
} catch (IOException e) {
System.err.println("Download failed!" + e.getMessage());
}
}, 0, 1, TimeUnit.DAYS);
}
private static void downloadFile(String fileUrl, String fileName) throws IOException {
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpget = new HttpGet(fileUrl);
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream inputStream = entity.getContent();
FileOutputStream outputStream = new FileOutputStream(new File(fileName));
int bytesRead = 0;
byte[] buffer = new byte[1024];
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
EntityUtils.consume(entity);
}
httpclient.close();
}
}
在上述代码中,我们使用了HttpGet请求来下载文件;在实际应用中,可以将文件下载包装成一个服务,按需进行调用。
示例一
我们以下载网络上的一张图片为例,实现文件的下载。
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class ImageDownloader {
private static final String IMAGE_URL = "https://example.com/image.jpg";
private static final String IMAGE_NAME = "image.jpg";
public static void main(String[] args) {
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpget = new HttpGet(IMAGE_URL);
try {
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream inputStream = entity.getContent();
FileOutputStream fileOutputStream = new FileOutputStream(new File(IMAGE_NAME));
int bytesRead = 0;
byte[] buffer = new byte[1024];
while ((bytesRead = inputStream.read(buffer)) != -1) {
fileOutputStream.write(buffer, 0, bytesRead);
}
fileOutputStream.close();
EntityUtils.consume(entity);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
在上述代码中,我们使用了HttpGet请求下载了一张图片,该图片的URL地址为:https://example.com/image.jpg,将下载的图片保存到了本地的文件中,文件名为:image.jpg。
示例二
我们以使用HttpClient下载一个CSV文件为例。
import java.io.*;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
public class CsvFileDownloader {
public static void main(String[] args) throws IOException {
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpget = new HttpGet("https://example.com/data.csv");
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream inputStream = entity.getContent();
writeInputStreamToFile(inputStream, "data.csv");
}
httpclient.close();
}
private static void writeInputStreamToFile(InputStream inputStream, String fileName) throws IOException {
OutputStream outputStream = new FileOutputStream(new File(fileName));
int bytesRead = 0;
byte[] buffer = new byte[1024];
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
}
}
在上述代码中,我们使用了HttpGet请求下载了一个CSV文件,该文件的URL地址为:https://example.com/data.csv,将下载的CSV文件保存到了本地的文件中,文件名为:data.csv。
总结:以上是使用Java及HttpClient实现文件下载的完整攻略及两个示例说明。在实际项目中,HttpClient可以支持证书、代理、cookies、连接池等功能,使得实现更加强大和灵活。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Java使用HttpClient实现文件下载 - Python技术站