在 Java 中下载网络文件(如通过 HTTP/HTTPS 链接下载文件)有多种常见方式。下面按从简单到灵活的顺序介绍几种常用方法,并给出示例代码。
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("下载完成");
}
}
✅ 可控性强
❌ 代码稍多
适合企业项目、复杂网络环境
<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("下载完成");
}
}
RestTemplateRestTemplate restTemplate = new RestTemplate();
ResponseEntity<byte[]> response = restTemplate.getForEntity(url, byte[].class);
Files.write(Paths.get("D:/file.jpg"), response.getBody());
Range 请求头HttpURLConnection / HttpClient 都支持| 场景 | 推荐方式 |
|---|---|
| 学习 / 小工具 | Files.copy |
| 普通下载 | HttpURLConnection |
| 企业项目 | Apache HttpClient |
| Spring 项目 | RestTemplate / WebClient |
如果你有具体需求(如:大文件、断点续传、带鉴权、Spring Boot),可以告诉我,我可以给你更精准的示例。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。