【问题标题】:Java: can't get html from URL [duplicate]Java:无法从 URL 获取 html [重复]
【发布时间】:2015-05-23 15:30:09
【问题描述】:

我正在尝试从 URL 读取 html 文件。我的代码适用于大多数网站,但其中一些网站除外,例如http://dota2.gamepedia.com/Dota_2_Wiki。我想我需要设置java代理什么的?...

这是我的代码:

    try {
        URL webPage = new URL("http://dota2.gamepedia.com/Dota_2_Wiki");

        URLConnection con = webPage.openConnection();
        con.setConnectTimeout(5000);
        con.setReadTimeout(5000);

        BufferedReader in = new BufferedReader(
                            newInputStreamReader(con.getInputStream()));

        String inputLine;
        while ((inputLine = in.readLine()) != null)
            System.out.println(inputLine);

        in.close();
    }
    catch (MalformedURLException exc){exc.printStackTrace();}
    catch (IOException exc){exc.printStackTrace();}

结果:

java.io.IOException: Server returned HTTP response code: 403 for URL: http://dota2.gamepedia.com/Dota_2_Wiki
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1838)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1439)
at com.Popov.Main.main(Main.java:17)

错误代码 403:如何访问它?顺便说一句,它在浏览器中正常工作

【问题讨论】:

  • 没有错误。进程以退出代码 0 结束。没有将 html 打印到控制台,例如 URL 为空。
  • 你在哪里知道的。您在不记录异常的情况下捕获异常。那是非常糟糕的编程。
  • 是的,对不起,我是编程的初学者。收到错误代码,已编辑帖子
  • "403 Forbidden" 你好像没有权限打开这个网站。
  • 是的,但是为什么我可以用浏览器打开,正常吗?..

标签: java html url


【解决方案1】:

您的问题很可能是因为没有正确设置用户代理。对于喜欢香草Java的你们。这些是代码

private void sendGet() throws Exception {

    String url = "http://dota2.gamepedia.com/Dota_2_Wiki";

    URL obj = new URL(url);
    CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL));
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();

    con.setRequestMethod("GET");
    con.setRequestProperty("User-Agent", USER_AGENT);

    int responseCode = con.getResponseCode();
    System.out.println("\nSending 'GET' request to URL : " + url);
    System.out.println("Response Code : " + responseCode);

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

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

    System.out.println(response.toString());

}

请注意,您还需要设置 cookie,因为当我尝试不使用它时,代码会给我很多重定向循环

【讨论】:

  • 谢谢,完美运行,现在我明白了。
【解决方案2】:

您可以简单地尝试使用jsoup html解析器。查看示例代码;

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

        Document doc = Jsoup
                .connect("http://dota2.gamepedia.com/Dota_2_Wiki")
                .userAgent(
                        "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.110 Safari/537.36")
                .timeout(0).followRedirects(true).execute().parse();
        Elements titles = doc.select(".entrytitle");

        // print all titles in main page
        for (Element e : titles) {
            System.out.println("text: " + e.text());
            System.out.println("html: " + e.html());
        }

        // print all available links on page
        Elements links = doc.select("a[href]");
        for (Element l : links) {
            System.out.println("link: " + l.attr("abs:href"));
        }

    }

【讨论】:

  • 谢谢,当然可以,但我想知道为什么没有外部库它就不能工作
【解决方案3】:

我认为您的问题是服务器不接受您的“用户代理”字符串并返回 403 禁止代码。

一个答案建议使用 Jsoup 并手动设置用户代理,但没有说明设置用户代理是关键步骤。您可以使用这种方法。

或者,您可以阅读Setting user agent of a java URLConnection 并自己设置 URLConnection 的用户代理。这种方法不需要任何外部库。

【讨论】:

    猜你喜欢
    • 2019-06-29
    • 2011-12-29
    • 1970-01-01
    • 2014-12-19
    • 2021-07-08
    • 1970-01-01
    • 2014-07-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多