服务器返回HTTP响应代码:406一个URL

时间:2018-04-18 13:17:40

标签: java web-crawler jsoup httpurlconnection

我正在使用Java和HttpURLConnection编写一个Web爬虫,这是我得到的错误:

java.io.IOException: Server returned HTTP response code: 406 for URL: https://www.mkyong.com/kotlin/kotlin-how-to-loop-a-map/
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(Unknown Source)
at testing.HttpURLConnectionGo.sendGet(HttpURLConnectionGo.java:34)
at testing.DefinitelyNotSpiderLeg.crawl(DefinitelyNotSpiderLeg.java:55)
at testing.DefinitelyNotSpider.search(DefinitelyNotSpider.java:33)
at testing.Test.main(Test.java:9)

这是我用于连接的方法:

// HTTP GET request
public String sendGet(String url) throws Exception {

    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();

    // optional default is GET
    con.setRequestMethod("GET");

    //add request header
    con.setRequestProperty("User-Agent", USER_AGENT);

    BufferedReader in = new BufferedReader(
            new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();

    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();
    return response.toString();
}

然后我使用Jsoup在另一个类中获取String:

String html = http.sendGet(url);
Document doc = Jsoup.parse(html);

为什么我会收到此错误?

1 个答案:

答案 0 :(得分:0)

HTTP 406是" Not Acceptable"的状态。每HTTP.CATMozilla。 Mozilla的参考继续说错误是罕见的,通常意味着

  

表示与可接受值列表匹配的响应   在Accept-Charset和Accept-Language中定义的服务无法提供。

您可以尝试在请求中设置这些标头。

您正在点击的网址也可能有一些机器人或抓取工具检测逻辑,并且正在返回406,因为该行为是“不可接受的”#34;。该用例不是理想的错误代码,但它是有道理的。