【问题标题】:Java - Not getting html code from a URL [duplicate]Java - 没有从 URL 获取 html 代码 [重复]
【发布时间】:2011-12-29 20:00:07
【问题描述】:

我要获取https://www2.cslb.ca.gov/OnlineServices/CheckLicenseII/LicenseDetail.aspx?LicNum=872423的html源码 为此,我正在使用这种方法,但没有获得 html 源代码。

public static String getHTML(URL url) {
    HttpURLConnection conn; // The actual connection to the web page
    BufferedReader rd; // Used to read results from the web page
    String line; // An individual line of the web page HTML
    String result = ""; // A long string containing all the HTML
    try {
        conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        while ((line = rd.readLine()) != null) {
            result += line;
        }
        rd.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return result;
}

【问题讨论】:

  • rd.readLine() 行第一次为空。
  • 你能给我们提供更多的背景信息吗? “没有得到 html 源代码”是什么意思?
  • @JavierIEH 方法返回空字符串
  • 你试过curl(命令行工具)来获取html吗?某些网站会检查请求是否来自网络浏览器。
  • @gigadot 我认为服务器可以通过查看User-Agent http 标头来判断请求是否来自浏览器。还有其他方法可以检查吗?

标签: java html url httpurlconnection


【解决方案1】:

服务器过滤掉 Java 的默认 User-Agent。这有效:

public static String getHTML(URL url) {
    try {
        final URLConnection urlConnection = url.openConnection();
        urlConnection.addRequestProperty("User-Agent", "Foo?");
        final InputStream inputStream = urlConnection.getInputStream();
        final String html = IOUtils.toString(inputStream);
        inputStream.close();
        return html;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

看起来用户代理被列入黑名单。默认情况下,我的 JDK 发送:

User-Agent: Java/1.6.0_26

请注意,我使用IOUtils 类来简化示例,但关键是:

urlConnection.addRequestProperty("User-Agent", "Foo?");

【讨论】:

  • +1 太棒了...它正在工作
猜你喜欢
  • 2017-03-21
  • 2015-05-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-21
相关资源
最近更新 更多