Hàm java save ảnh từ 1 URL bị chặm không cho tải ảnh về
Nếu bạn gặp vấn đề khi tải ảnh từ một URL trong Java, có thể do một số nguyên nhân như trang web chặn việc tải xuống, cần xác thực, hoặc đơn giản là URL không hợp lệ. Dưới đây là một ví dụ đơn giản về cách tải ảnh từ một URL, cùng với một số bước để xử lý vấn đề.
Mã nguồn ví dụ#
` import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardCopyOption;
public class ImageDownloader {
public static void downloadImage(String imageUrl, String destinationFilePath) {
try {
URL url = new URL(imageUrl);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setConnectTimeout(5000);
httpURLConnection.setReadTimeout(5000);
// Kiểm tra mã phản hồi
int responseCode = httpURLConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
try (InputStream inputStream = httpURLConnection.getInputStream();
OutputStream outputStream = Files.newOutputStream(Path.of(destinationFilePath))) {
Files.copy(inputStream, Path.of(destinationFilePath), StandardCopyOption.REPLACE_EXISTING);
System.out.println("Image downloaded successfully: " + destinationFilePath);
}
} else {
System.out.println("Failed to download image. Response code: " + responseCode);
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
String imageUrl = "https://example.com/image.jpg"; // Thay thế bằng URL của bạn
String destinationFilePath = "downloaded_image.jpg"; // Đường dẫn lưu ảnh
downloadImage(imageUrl, destinationFilePath);
}
} `
Một số điều cần lưu ý#
Chứng thực: Nếu URL yêu cầu xác thực (như Basic Auth), bạn cần thêm thông tin xác thực vào tiêu đề của yêu cầu.
Headers: Một số trang web có thể yêu cầu bạn thêm một số headers nhất định như User-Agent. Bạn có thể làm như sau:
httpURLConnection.setRequestProperty("User-Agent", "Mozilla/5.0");
Chặn tải xuống: Một số trang web có thể có cơ chế bảo vệ chống lại việc tải xuống tự động. Nếu bạn gặp phải trường hợp này, hãy xem xét việc tìm hiểu chính sách của trang web hoặc sử dụng API chính thức nếu có.
Thử nghiệm với URL khác: Để xác định liệu vấn đề có phải do URL cụ thể hay không, bạn có thể thử tải xuống từ các URL khác mà bạn biết là hoạt động.
Nếu bạn vẫn gặp vấn đề, hãy cung cấp thêm thông tin chi tiết về lỗi hoặc hành vi của chương trình để mình có thể giúp đỡ tốt hơn!
`
public void saveImageOk(String imageUrl, String destinationFile) throws Exception { // Tạo URL từ đường dẫn ảnh URL url = new URL(imageUrl);
// Mở kết nối với URL
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// Thêm User-Agent giả lập trình duyệt
//connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36");
connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36");
connection.setRequestProperty("Referer", "https://domain-chan-save-anh.com");
connection.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
connection.setRequestProperty("Accept-Encoding", "gzip, deflate, br");
// Kiểm tra mã phản hồi
int responseCode = connection.getResponseCode();
if (responseCode != HttpURLConnection.HTTP_OK) {
throw new Exception("Failed to connect, HTTP response code: " + responseCode);
}
// Mở luồng đầu vào từ kết nối
InputStream inputStream = connection.getInputStream();
OutputStream outputStream = new FileOutputStream(destinationFile);
// Tạo bộ đệm để lưu dữ liệu
byte[] buffer = new byte[2048];
int bytesRead;
// Đọc dữ liệu từ URL và ghi vào file
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
// Đóng các luồng
inputStream.close();
outputStream.close();
// System.out.println("Image saved to " + destinationFile);
}
`