java如何下载图片
使用 HttpURLConnection 下载图片
通过 HttpURLConnection 建立网络连接,读取输入流并保存为本地文件。适用于基础场景,无需依赖第三方库。
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class ImageDownloader {
public static void downloadImage(String imageUrl, String destinationPath) throws Exception {
URL url = new URL(imageUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
try (InputStream in = connection.getInputStream();
FileOutputStream out = new FileOutputStream(destinationPath)) {
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
}
}
connection.disconnect();
}
}
使用 Apache HttpClient 下载图片
通过 HttpClient 库实现更灵活的请求配置和响应处理。需添加依赖:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
实现代码:
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import java.io.FileOutputStream;
import java.io.InputStream;
public class HttpClientDownloader {
public static void download(String imageUrl, String savePath) throws Exception {
try (CloseableHttpClient client = HttpClients.createDefault()) {
HttpGet request = new HttpGet(imageUrl);
try (CloseableHttpResponse response = client.execute(request)) {
HttpEntity entity = response.getEntity();
if (entity != null) {
try (InputStream in = entity.getContent();
FileOutputStream out = new FileOutputStream(savePath)) {
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
}
}
}
}
}
}
}
使用 Java NIO 高效传输
通过 Files.copy() 方法实现高效文件传输,适用于 Java 7+ 环境:
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
public class NioDownloader {
public static void download(String imageUrl, String savePath) throws Exception {
try (InputStream in = new URL(imageUrl).openStream()) {
Files.copy(in, Paths.get(savePath), StandardCopyOption.REPLACE_EXISTING);
}
}
}
异常处理建议
所有方法均应添加以下异常处理逻辑:

try {
// 调用下载方法
} catch (MalformedURLException e) {
System.err.println("URL格式错误: " + e.getMessage());
} catch (IOException e) {
System.err.println("IO异常: " + e.getMessage());
} catch (Exception e) {
System.err.println("未知错误: " + e.getMessage());
}
性能优化要点
- 大文件下载时使用缓冲池(BufferPool)
- 设置连接超时参数(建议 10-30 秒)
- 对 HTTPS 链接需配置 SSL 上下文
- 考虑使用断点续传功能(需服务器支持 Range 头)






