【问题标题】:Server returned HTTP response code: 406 a URL服务器返回 HTTP 响应代码:406 一个 URL
【发布时间】:2018-04-18 13:17:39
【问题描述】:

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

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);

为什么会出现这个错误?

【问题讨论】:

    标签: java web-crawler jsoup httpurlconnection


    【解决方案1】:

    根据HTTP.CATMozilla,HTTP 406 是“不可接受”的状态。 Mozilla 参考继续说该错误很少见,通常意味着

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

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

    您访问的 URL 也有可能具有某些机器人或爬虫检测逻辑,并且由于该行为“不可接受”而返回 406。该用例不是理想的错误代码,但很有意义。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-24
      • 2014-08-09
      • 2013-09-12
      • 1970-01-01
      • 2011-04-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多