【问题标题】:Java URL - Server Response 416 error codeJava URL - 服务器响应 416 错误代码
【发布时间】:2015-11-24 14:47:58
【问题描述】:

我正在尝试获取我曾经建立的特定网站的 html 源代码。但是我继续收到此错误:

java.io.IOException: Server returned HTTP response code: 416 for URL: http://www.website.com/
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1838)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1439)
    at main.getHTMLContent(main.java:37)
    at main.getEventLinks(main.java:69)
    at main.main(main.java:21)
Exception in thread "main" java.lang.NullPointerException
    at main.getEventLinks(main.java:72)
    at main.main(main.java:21)

我做了一些研究,但找不到可能的解决方案。

我知道 416 是:

Web 服务器(运行网站)认为客户端(例如您的 Web 浏览器或我们的 CheckUpDown 机器人)发送的 HTTP 数据流包含一个“范围”请求,该请求指定了无法满足的字节范围 -因为被访问的资源没有覆盖这个字节范围。例如,如果资源 - 例如图像文件 - 有 1000 字节并且请求的范围是 500-1500,则它不能满足。

通过http://www.checkupdown.com/status/E416.html

我找到了这个解决方案,但我无权访问服务器。

416 Requested Range Not Satisfiable

如果您知道解决此问题的方法,那将会很有帮助。我也对可能的替代方案持开放态度。

这是发出请求的代码:

protected  static ArrayList<String> getHTMLContent(String u){
    URL url;
    ArrayList<String> linesOfHTML = new ArrayList<>();
    try {
        // get URL content

        //String a="http://localhost:8080//TestWeb/index.jsp";
        url = new URL(u);
        URLConnection conn = url.openConnection();

        // open the stream and put it into BufferedReader
        BufferedReader br = new BufferedReader(
                           new InputStreamReader(conn.getInputStream()));

        String inputLine;
        while ((inputLine = br.readLine()) != null) {
                System.out.println(inputLine);
                if(!inputLine.equals("")){
                    linesOfHTML.add(inputLine);
                }
        }
        br.close();

        System.out.println("Done");
        return null;

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

【问题讨论】:

    标签: java url server


    【解决方案1】:

    我知道我很晚了,但我的回答可能会有所帮助。通过设置请求标头我解决了问题

    conn.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); 
    

    或者它可能只返回您必须编写的 json 格式的返回响应

    conn.setRequestProperty("Accept" ,"application/json"); 
    

    但请注意,如果服务器故意阻止您,此代码将不起作用。

    【讨论】:

    • 如果其他人,可以验证这一点。我没有环境设置。我会把它标记为正确的。
    猜你喜欢
    • 2014-02-22
    • 2013-08-12
    • 1970-01-01
    • 1970-01-01
    • 2018-04-24
    • 2014-08-09
    • 2020-11-28
    • 2016-05-24
    • 2019-02-01
    相关资源
    最近更新 更多