温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

java网络文件如何下载

发布时间:2026-10-24 05:56:13 来源:亿速云 阅读:100 作者:小樊 栏目:编程语言

在 Java 中下载网络文件(如通过 HTTP/HTTPS 链接下载文件)有多种常见方式。下面按从简单到灵活的顺序介绍几种常用方法,并给出示例代码。


一、最简单方式(Java 7+):Files.copy(推荐入门)

适合简单下载,不支持复杂配置(如请求头、超时)。

import java.io.InputStream;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;

public class DownloadDemo {
    public static void main(String[] args) throws Exception {
        String fileUrl = "https://example.com/test.jpg";
        String savePath = "D:/test.jpg";

        try (InputStream in = new URL(fileUrl).openStream()) {
            Files.copy(in, Paths.get(savePath));
        }
        System.out.println("下载完成");
    }
}

✅ 优点:代码少
❌ 缺点:不能设置超时、Header、代理


二、常用方式:HttpURLConnection(标准库)

适合需要控制请求参数的场景。

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpDownload {
    public static void main(String[] args) throws IOException {
        String fileUrl = "https://example.com/test.pdf";
        String savePath = "D:/test.pdf";

        HttpURLConnection conn = (HttpURLConnection) new URL(fileUrl).openConnection();
        conn.setRequestMethod("GET");
        conn.setConnectTimeout(5000);
        conn.setReadTimeout(5000);

        try (InputStream in = conn.getInputStream();
             FileOutputStream out = new FileOutputStream(savePath)) {

            byte[] buffer = new byte[4096];
            int len;
            while ((len = in.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }
        }
        System.out.println("下载完成");
    }
}

✅ 可控性强
❌ 代码稍多


三、推荐方式(生产级):Apache HttpClient

适合企业项目、复杂网络环境

Maven 依赖

<dependency>
    <groupId>org.apache.httpcomponents.client5</groupId>
    <artifactId>httpclient5</artifactId>
    <version>5.3</version>
</dependency>

示例代码

import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.io.entity.EntityUtils;

import java.io.FileOutputStream;
import java.io.InputStream;

public class HttpClientDownload {
    public static void main(String[] args) throws Exception {
        String url = "https://example.com/test.zip";
        String savePath = "D:/test.zip";

        try (CloseableHttpClient client = HttpClients.createDefault()) {
            HttpGet get = new HttpGet(url);
            client.execute(get, response -> {
                try (InputStream in = response.getEntity().getContent();
                     FileOutputStream out = new FileOutputStream(savePath)) {
                    byte[] buf = new byte[4096];
                    int len;
                    while ((len = in.read(buf)) != -1) {
                        out.write(buf, 0, len);
                    }
                }
                return null;
            });
        }
        System.out.println("下载完成");
    }
}

四、Spring Boot 项目:RestTemplate

RestTemplate restTemplate = new RestTemplate();
ResponseEntity<byte[]> response = restTemplate.getForEntity(url, byte[].class);
Files.write(Paths.get("D:/file.jpg"), response.getBody());

五、常见问题

1️⃣ HTTPS 证书问题

  • 公网正常证书:无需处理
  • 自签名证书:需忽略 SSL 校验(不推荐生产)

2️⃣ 大文件下载

  • 使用流式读写
  • 不要一次性读入内存

3️⃣ 断点续传

  • 使用 Range 请求头
  • HttpURLConnection / HttpClient 都支持

六、总结建议

场景 推荐方式
学习 / 小工具 Files.copy
普通下载 HttpURLConnection
企业项目 Apache HttpClient
Spring 项目 RestTemplate / WebClient

如果你有具体需求(如:大文件、断点续传、带鉴权、Spring Boot),可以告诉我,我可以给你更精准的示例。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI
助
手