Java使用HttpClient实现文件下载

下面是使用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实现文件下载的主要步骤如下:

  1. 创建HttpClient实例。

  2. 创建HttpGet实例,并设置下载文件的URL地址。

  3. 执行HttpGet请求,获取文件内容,并将内容写入到文件中。

  4. 关闭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技术站

(0)
上一篇 2023年6月27日
下一篇 2023年6月27日

相关文章

  • nginx配置ssl双向验证的方法

    配置 SSL 双向验证需要以下步骤: 生成证书 首先安装 Open SSL。在 Linux 系统上可以使用以下命令安装: sudo apt-get install openssl 下面是一个生成 SSL 证书的示例命令: openssl req -new -x509 -days 3650 -nodes -out server.crt -keyout serv…

    other 2023年6月27日
    00
  • C++类继承时的构造函数

    在C++类的继承中, 子类不仅要继承父类的属性和方法,而且还要继承其构造函数和析构函数。本文将详细讲解在C++类继承时的构造函数。 构造函数和析构函数的继承规则 在C++中,子类的构造函数和析构函数会默认调用父类的构造函数和析构函数。具体规则如下: 子类的构造函数会默认调用父类的无参构造函数。 如果父类没有无参构造函数,则必须在子类的构造函数中显示的调用父类…

    other 2023年6月26日
    00
  • 自定义Dialog弹框和其背景阴影显示方法

    当我们需要在应用程序中创建自定义的对话框弹框时,可以使用以下步骤来实现: 创建自定义布局文件:首先,我们需要创建一个自定义的布局文件,用于定义对话框的外观和内容。可以使用XML文件来定义布局,例如,创建一个名为custom_dialog.xml的文件。 <LinearLayout xmlns:android=\"http://schemas.…

    other 2023年9月7日
    00
  • vite+vue3中使用mock模拟数据问题

    vite+vue3的开发中,我们希望在开发过程中使用mock数据进行测试,而不是依赖于后端API接口。这样可以在不影响后端开发的情况下,快速开发并测试前端页面。在这里,我们提供一个完整的攻略,介绍如何在vite+vue3中使用mock模拟数据。 1. 安装mockjs 首先,在项目根目录下,使用npm或者yarn安装mockjs: npm install m…

    other 2023年6月27日
    00
  • 前端开发必须知道的JS之闭包及应用

    当然!下面是关于\”前端开发必须知道的JS之闭包及应用\”的完整攻略,包含两个示例说明。 闭包及应用 闭包是 JavaScript 中一个重要的概念,它可以帮助我们在函数内部创建和访问私有变量,并且在函数执行完毕后仍然保持对这些变量的访问。 以下是一些关于闭包的重要概念和应用: 创建闭包:在 JavaScript 中,当一个函数内部定义了另一个函数,并且内部…

    other 2023年8月20日
    00
  • SQL Server解析/操作Json格式字段数据的方法实例

    SQL Server 解析/操作 Json 格式字段数据的方法实例 SQL Server 是一个功能强大的关系型数据库管理系统,它可以轻松地操作和解析 Json 格式字段数据,这对于存储和处理各种数据类型的应用程序来说非常有用。本文将介绍 SQL Server 解析/操作 Json 格式字段数据的详细攻略,其中包含两个示例说明。 Json 格式字段数据的基本…

    other 2023年6月25日
    00
  • Android实现360手机助手底部的动画菜单

    Android实现360手机助手底部的动画菜单攻略 1. 概述 在Android应用中实现底部的动画菜单可以提升用户体验和界面交互效果。本攻略将详细介绍如何实现类似360手机助手底部的动画菜单效果。 2. 实现步骤 以下是实现该效果的步骤: 步骤1:准备工作 首先,确保你的Android项目已经创建并配置好。在项目的布局文件中,添加一个底部菜单的容器布局,例…

    other 2023年9月7日
    00
  • 前端pdf文件转图片方法

    当然,我很乐意为您提供前端PDF文件转图片的完整攻略。以下是详细的步骤和示例: 步骤1:了解前端PDF文件转图片的方法 前端PDF文件转图片的方法是使用JavaScript库将PDF转换为图片。这种方法可以在浏览器中直接运行,无需服务器端的支持。 步骤2:下载并安装pdf.js pdf.js是一个开源的JavaScript库,用于在浏览器中渲染PDF文件。您…

    other 2023年5月6日
    00
合作推广
合作推广
分享本页
返回顶部