我有一些设备,当您通过 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/