Lỗi 406 khi download ảnh

Em đang sử dụng Jsoup để download ảnh từ link sau: http://www.allitebooks.in/pcs-just-the-steps-for-dummies-2nd-edition/ nhưng khi em sử dụng đoạn code sau để download ảnh về local thì gặp lỗi 406

package test;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class TestGetCategory {

	private static String IMAGE_DESTINATION_FOLDER = "C:/images";

	public static void main(String[] args) throws IOException {

		// replace it with your URL
		String strURL = "http://www.allitebooks.in/pcs-just-the-steps-for-dummies-2nd-edition/";

		// connect to the website and get the document
		Document document = Jsoup.connect(strURL).userAgent("Mozilla/5.0").timeout(10 * 1000).get();

		// select all img tags
		Elements imageElements = document.select("div.td-post-content > p:eq(0) > img");

		// iterate over each image
		for (Element imageElement : imageElements) {

			// make sure to get the absolute URL using abs: prefix
			String strImageURL = imageElement.attr("abs:src");

			// download image one by one
			downloadImage(strImageURL);
		}
	}

	private static void downloadImage(String strImageURL) {

		// get file name from image path
		String strImageName = strImageURL.substring(strImageURL.lastIndexOf("/") + 1);

		System.out.println("Saving: " + strImageName + ", from: " + strImageURL);

		try {

			// open the stream from URL
			URL urlImage = new URL(strImageURL);
			InputStream in = urlImage.openStream();

			byte[] buffer = new byte[4096];
			int n = -1;

			OutputStream os = new FileOutputStream(IMAGE_DESTINATION_FOLDER + "/" + strImageName);

			// write bytes to the output stream
			while ((n = in.read(buffer)) != -1) {
				os.write(buffer, 0, n);
			}

			// close the stream
			os.close();

			System.out.println("Image saved");

		} catch (IOException e) {
			e.printStackTrace();
		}

	}
}
Exception in thread "main" org.jsoup.HttpStatusException: HTTP error fetching URL. Status=406, URL=http://www.allitebooks.in/pcs-just-the-steps-for-dummies-2nd-edition/
	at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:776)
	at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:722)
	at org.jsoup.helper.HttpConnection.execute(HttpConnection.java:306)
	at org.jsoup.helper.HttpConnection.get(HttpConnection.java:295)
	at test.TestGetCategory.main(TestGetCategory.java:24)

Em có tham khảo một bài trên mạng nhưng em đọc không hiểu cho lắm (https://stackoverflow.com/questions/51777354/jsoup-connection-http-error-406)
Mong được anh/chị giúp đỡ. Em cảm ơn anh/chị nhiều ạ !

406 Not Acceptable: một số trường ở Header không được chấp nhận, cũng có thể do userAgent("Mozilla/5.0") chưa đầy đủ, hoặc cần thêm một số trường khác trong: https://en.m.wikipedia.org/wiki/List_of_HTTP_header_fields#Request_fields
Có nhiều trang yêu cầu phần đầu (header) rất cao, để tránh những trường hợp như bạn đang muốn.

2 Likes

Khi em chỉ rõ user agent

Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36

thì bị một lỗi khác đó là:

Saving: PCs-Just-the-Steps-For-Dummies-2nd-Edition-300x240.jpg, from: http://www.allitebooks.in/wp-content/uploads/2019/03/PCs-Just-the-Steps-For-Dummies-2nd-Edition-300x240.jpg
java.io.IOException: Server returned HTTP response code: 403 for URL: http://www.allitebooks.in/wp-content/uploads/2019/03/PCs-Just-the-Steps-For-Dummies-2nd-Edition-300x240.jpg
	at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(Unknown Source)
	at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
	at java.net.URL.openStream(Unknown Source)
	at test.TestGetCategory.downloadImage(TestGetCategory.java:51)
	at test.TestGetCategory.main(TestGetCategory.java:36)

mà em google thì nó lại bảo chỉ ra user agent
(https://www.javacodeexamples.com/jsoup-error-403-forbidden-exception-fix/780)
Em đã chỉ ra user agent mà không sửa được. Anh có solution gì giúp em với ạ ? Em cảm ơn !

Thử “sao chép” các thông tin được trình duyệt gửi thử xem. Trang này sẽ liệt kê các thông tin đó, bạn gán hết vào kết nối JSoup của bạn: https://www.whatismybrowser.com/detect/what-http-headers-is-my-browser-sending
Ví dụ:

Khóa Giá trị
ACCEPT text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,/;q=0.8,application/signed-exchange;v=b3
ACCEPT_ENCODING gzip, deflate, br
ACCEPT_LANGUAGE vi-VN,vi;q=0.9,en;q=0.8,en-US;q=0.7,fr-FR;q=0.6,fr;q=0.5
HOST www.whatismybrowser.com
REFERER https://www.google.com/
SAVE_DATA on
UPGRADE_INSECURE_REQUESTS 1
USER_AGENT Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36

Khi đó ta có thể “sao chép” một cách linh hoạt sang JSoup:

		// connect to the website and get the document
		Document document = Jsoup.connect(strURL)
.header("ACCEPT","text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3")
.header("ACCEPT_ENCODING","gzip, deflate, br")
.header("ACCEPT_LANGUAGE","vi-VN,vi;q=0.9,en;q=0.8,en-US;q=0.7,fr-FR;q=0.6,fr;q=0.5")
.header("HOST","http://www.allitebooks.in/") // đúng tên máy chủ nhé.
.header("REFERER","https://www.google.com/")
//.userAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36")
.header("USER_AGENT","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36")

//.header("...","...") // thêm nữa nếu cần
.timeout(10 * 1000).get();


1 Like
83% thành viên diễn đàn không hỏi bài tập, còn bạn thì sao?