温馨提示×

温馨提示×

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

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

java怎么下载网络文件

发布时间:2026-09-13 00:55:33 来源:亿速云 阅读:96 作者:小樊 栏目:编程语言

在 Java 中下载网络文件 commonly 有几种方式,下面按常见程度给你示例,从最简单到更灵活。


一、使用 java.net.URL(最基础,JDK 自带)

适合简单下载,不需要额外依赖。

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

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

        try (InputStream in = new URL(fileUrl).openStream();
             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("下载完成");
        }
    }
}

✅ 优点:无需依赖
❌ 缺点:功能少(不支持超时、Header、重试)


二、使用 HttpURLConnection(可控性更强)

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

public class HttpDownload {
    public static void main(String[] args) throws IOException {
        URL url = new URL("https://example.com/file.zip");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setConnectTimeout(5000);
        conn.setReadTimeout(10000);

        try (InputStream in = conn.getInputStream();
             FileOutputStream out = new FileOutputStream("D:/file.zip")) {

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

✅ 可设置超时、请求头
❌ 代码稍多


三、使用 Apache HttpClient(推荐,企业常用)

1️⃣ 添加依赖(Maven)

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

2️⃣ 示例代码

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 {
        try (CloseableHttpClient client = HttpClients.createDefault()) {
            HttpGet get = new HttpGet("https://example.com/file.pdf");
            client.execute(get, response -> {
                try (InputStream in = response.getEntity().getContent();
                     FileOutputStream out = new FileOutputStream("D:/file.pdf")) {
                    byte[] buf = new byte[8192];
                    int len;
                    while ((len = in.read(buf)) != -1) {
                        out.write(buf, 0, len);
                    }
                }
                return null;
            });
        }
        System.out.println("下载完成");
    }
}

✅ 支持 HTTPS、代理、重试、Header
✅ 生产级方案


四、Java 11+ 的 HttpClient(官方现代方案)

import java.net.http.*;
import java.net.URI;
import java.nio.file.*;

public class Java11Download {
    public static void main(String[] args) throws Exception {
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create("https://example.com/file.txt"))
                .build();

        HttpResponse<Path> response = client.send(
                request,
                HttpResponse.BodyHandlers.ofFile(Paths.get("D:/file.txt"))
        );

        System.out.println("状态:" + response.statusCode());
    }
}

✅ 官方推荐
✅ 代码简洁


五、常见注意点

  • ✅ 大文件:用 流(InputStream) 边读边写,不要一次性加载
  • ✅ HTTPS:Java 默认支持
  • ✅ 中文 URL:使用 URLEncoder.encode
  • ✅ 断点续传:需要 Range 请求头(可帮你写)

如果你告诉我:

  • Java 版本
  • 是否用 Maven / Spring
  • 是否大文件 / 是否需要断点续传

我可以给你最合适的完整示例。

向AI问一下细节

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

AI
助
手