Java - 无法从 URL 获取 html 代码

标签 java html url httpurlconnection

我想获取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;
}

最佳答案

服务器过滤掉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?");

关于Java - 无法从 URL 获取 html 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8142039/

相关文章:

javascript - 使用 jquery 显示两个数据透视表

java - 创建一个包含 '&' 的 url

java - 智能 : How to use No Layout or Absolute Layout like Eclipse?

java - 从列表中删除第一个 'n' 元素而不进行迭代

Java - 将字符串转换为 ISO 8601 日期格式错误 Joda-Time

mysql - 如果 URL 被访问则更新 MySQL 数据

javascript - 结合 Bookmarklet 来创建 HTTP 和 HTTPS 之间的切换?

java - 如何使用java byte[]准确发送如此复杂的十六进制、二进制协议(protocol)数据?

html - 字体粗细值不起作用

javascript - 去除 iFrame 的 html 标签样式