java 如何下载照片
下载照片的方法
使用Java下载照片可以通过多种方式实现,以下是几种常见的方法。
使用java.net.URL和java.nio.file.Files
通过URL类打开网络连接,使用Files.copy将数据流保存到本地文件。
import java.io.IOException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
public class DownloadImage {
public static void download(String imageUrl, String destinationPath) throws IOException {
URL url = new URL(imageUrl);
Files.copy(url.openStream(), Paths.get(destinationPath));
}
}
使用HttpURLConnection
通过HttpURLConnection可以更灵活地处理HTTP请求,例如设置请求头或处理重定向。
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class DownloadImage {
public static void download(String imageUrl, String destinationPath) throws IOException {
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);
}
}
}
}
使用Apache HttpClient
如果需要更高级的功能(如处理Cookie或HTTPS),可以使用Apache HttpClient库。

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 DownloadImage {
public static void download(String imageUrl, String destinationPath) throws Exception {
try (CloseableHttpClient client = HttpClients.createDefault()) {
HttpGet request = new HttpGet(imageUrl);
try (CloseableHttpResponse response = client.execute(request);
InputStream in = response.getEntity().getContent();
FileOutputStream out = new FileOutputStream(destinationPath)) {
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
}
}
}
}
}
注意事项
- 确保目标路径有写入权限。
- 处理异常情况,例如网络错误或文件写入失败。
- 对于大文件下载,建议使用缓冲区以提高效率。
- 如果下载的是动态生成的图片,可能需要设置请求头(如
User-Agent)。






