我有设备发布一个HTML页面,当你通过他们的IP地址连接。例如,如果我要在计算机上转到“192.168.1.104”,我会看到设备发布的html页面。我想刮这个HTML,但我得到了一些错误,特别是在我的方法的第一行MalformedURLException。我在下面发布了我的方法。我发现了一些获取html的代码,并根据我的需要调整了它。谢谢java - 从IP地址获取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();
}
编辑:上面的代码已被更改为反映构建一个新的URL以正常工作与IP。但是,当我尝试从连接中获取contentType时,它是空的。
URL不能是IP地址 - 它应该是像 - http://192.168.1.104:8080/app/index.html – sanbhat 2013-04-29 18:19:14