在 Java 中实现网络文件下载,常见方式有以下几种,从简单到专业逐步说明。
URL + URLConnection(JDK 原生)适合简单下载,不依赖第三方库。
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
public class SimpleDownload {
public static void main(String[] args) throws IOException {
String fileUrl = "https://example.com/test.jpg";
String savePath = "D:/test.jpg";
URL url = new URL(fileUrl);
URLConnection conn = url.openConnection();
try (InputStream in = conn.getInputStream();
FileOutputStream out = new FileOutputStream(savePath)) {
byte[] buffer = new byte[8192];
int len;
while ((len = in.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
}
System.out.println("下载完成");
}
}
✅ 优点:无需依赖
❌ 缺点:功能有限(无超时、无重试、无进度)
HttpURLConnection(更可控)HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
conn.setReadTimeout(10000);
int code = conn.getResponseCode();
if (code == 200) {
// 下载逻辑同上
}
✅ 可设置超时、请求头
✅ 适合大多数场景
HttpClient(推荐)Java 11 自带 HTTP 客户端,支持异步、HTTPS。
import java.net.http.*;
import java.net.URI;
import java.nio.file.*;
public class HttpClientDownload {
public static void main(String[] args) throws Exception {
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://example.com/test.jpg"))
.build();
HttpResponse<Path> response = client.send(
request,
HttpResponse.BodyHandlers.ofFile(Paths.get("D:/test.jpg"))
);
System.out.println("状态码:" + response.statusCode());
}
}
✅ 官方推荐
✅ 支持异步、HTTPS、流式
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
适合:
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
</dependency>
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("https://example.com/test.jpg")
.build();
try (Response response = client.newCall(request).execute()) {
Files.write(Paths.get("D:/test.jpg"),
response.body().bytes());
}
✅ 简洁、性能好
✅ Android / 后端都常用
long total = conn.getContentLength();
long downloaded = 0;
while ((len = in.read(buf)) != -1) {
out.write(buf, 0, len);
downloaded += len;
System.out.println(downloaded * 100 / total + "%");
}
Range: bytes=1024-
| 场景 | 推荐 |
|---|---|
| 学习 / 简单工具 | URL / HttpURLConnection |
| Java 11+ 项目 | HttpClient |
| 企业级 / 复杂网络 | OkHttp / Apache |
| Android | OkHttp |
如果你愿意,我可以:
你打算用在什么场景?
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。