Search code examples
androidjsoup

Android. HTTP error fetching URL. Status=403


I'm trying to get data from site. When I use this code in Intellij IDEA everything works fine, but when I use this code in Android Studio and real device, I get:

org.jsoup.HttpStatusException: HTTP error fetching URL. Status=403

Here is my code:

private static final String URL = "http://www.openaip.net/airports?apttype_type_filter=All&country_filter=All&name_filter=EHAM";

private static final String useragent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) " +
                "AppleWebKit/537.36 (KHTML, like Gecko) " +
                "Chrome/52.0.2743.116 Safari/537.36";

Document document = Jsoup.connect(URL)
                        .userAgent(useragent)
                        .ignoreContentType(true)
                        .timeout(5000)
                        .execute() //  <-- on this line I get error
                        .parse();

All information that I have found is only about "userAgent()" method, but It didn't help.

UPD: Sorry, it was my bad in question. Correct url: http://www.openaip.net/airports?apttype_type_filter=All&country_filter=All&name_filter=EHAM, but I still have the same problem.

Error: org.jsoup.HttpStatusException: HTTP error fetching URL. Status=403, URL=http://www.openaip.net/airports?apttype_type_filter=All&country_filter=All&name_filter=EHAM


Solution

  • I've added the missing header in the request and I was able to retrieve the website content, the code I've used is:

    Document document = Jsoup.connect(URL)
                                .userAgent("Mozilla")
                                .header("Accept", "text/html")
                                .header("Accept-Encoding", "gzip,deflate")
                                .header("Accept-Language", "it-IT,en;q=0.8,en-US;q=0.6,de;q=0.4,it;q=0.2,es;q=0.2")
                                .header("Connection", "keep-alive")
                                .ignoreContentType(true)
                                .get();