java - 从ip地址获取html

标签 java url urlconnection

我有一些设备,当您通过 IP 地址连接时会发布 html 页面。例如,如果我在计算机上访问“192.168.1.104”,我会看到设备发布的 html 页面。我正在尝试抓取此 html,但出现了一些错误,特别是在我的方法的第一行出现 MalformedURLException。我在下面发布了我的方法。我找到了一些获取 html 的代码,并根据我的需要对其进行了调整。谢谢

public String getSbuHtml(String ipToPoll) throws IOException, SocketTimeoutException {
    URL url = new URL("http", ipToPoll, -1, "/");
    URLConnection con = url.openConnection();
    con.setConnectTimeout(1000);
    con.setReadTimeout(1000);
    Pattern p = Pattern.compile("text/html;\\s+charset=([^\\s]+)\\s*");
    Matcher m = p.matcher(con.getContentType());
    String charset = m.matches() ? m.group(1) : "ISO-8859-1";
    BufferedReader r = new BufferedReader(
            new InputStreamReader(con.getInputStream(), charset));
    String line = null;
    StringBuilder buf = new StringBuilder();
    while ((line = r.readLine()) != null) {
        buf.append(line).append(System.getProperty("line.separator"));
    }
    return buf.toString();
}

编辑:上面的代码已更改,以反射(reflect)构造新的 URL 以便与 IP 正常工作。但是,当我尝试从连接获取 contentType 时,它​​为空。

最佳答案

URL(统一资源定位器)必须具有资源来定位 (index.html) 以及方法网络通信 (http://)。因此有效 URL 的示例可以是

http://192.168.1.104:8080/app/index.html 

仅仅192.168.1.104并不代表URL

关于java - 从ip地址获取html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16285528/

相关文章:

java - Java 中的 Hello World : Understanding the concept versus in python

django - Django 中多个 View 中的相同 URL

javascript - 带有 URL 参数的 URL 在浏览器中连接起来

.htaccess 可以工作,但不允许我访问子文件夹中的博客 index.php

java - 工程格式化程序功能不上轮

java - 在 URL 中带有时间戳的 Spring RequestMapping

JRE 1.5 上的 java.lang.IllegalArgumentException : TLSv1. 2

java - URLConnection 超时错误在本地工作正常,但在开发服务器上不工作

php - 在 Android 中从 HTTP 请求读取结果

java - 根据方位角和距离计算纬度和经度