在 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("下载完成");
}
}
✅ 可设置超时、请求头
❌ 代码稍多
<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 {
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
✅ 生产级方案
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());
}
}
✅ 官方推荐
✅ 代码简洁
URLEncoder.encodeRange 请求头(可帮你写)如果你告诉我:
我可以给你最合适的完整示例。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。