Java通过图片链接下载图片到本地
时间: 2025-01-29 18:12:15 浏览: 45
在Java中,你可以使用HttpURLConnection或者第三方库如Apache HttpClient或OkHttp来下载图片。以下是一个简单的示例,展示如何使用HttpURLConnection从图片链接下载图片:
```java
import java.io.*;
import java.net.URL;
public class ImageDownloader {
public static void downloadImage(String imageUrl, String destinationPath) throws IOException {
URL url = new URL(imageUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
// 获取图片输入流
InputStream inputStream = connection.getInputStream();
FileOutputStream outputStream = new FileOutputStream(destinationPath);
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
// 关闭流
inputStream.close();
outputStream.close();
System.out.println("Image downloaded successfully at " + destinationPath);
} else {
throw new RuntimeException("Failed to download image. Response code: " + responseCode);
}
}
}
```
在这个例子中,你需要提供一个图片链接`imageUrl`和本地保存的路径`destinationPath`。这个函数会连接到URL、检查响应码(确认请求成功),然后读取并保存文件。
阅读全文
相关推荐
















