簡體   English   中英

java-從IP地址獲取HTML

[英]java - get html from ip address

當您通過其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();
}

編輯:上面的代碼已更改,以反映構造一個新的URL以與ip一起正常工作。 但是,當我嘗試從連接中獲取contentType時,它為null。

URL (統一資源定位器)必須具有資源index.html )以及網絡通信方式http:// )。 因此,有效網址的示例可以是

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

192.168.1.104不代表網址

您需要在傳遞給該方法的String的前面添加http://

創建您的URL,如下所示:

URL url = new URL("http", ipToPoll, -1, "/");

而且由於您正在閱讀可能很長的HTML頁面,所以我認為緩沖在這里會有所幫助:

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();


編輯 :響應您的contentType出現空問題。

在檢查任何類似於getContentType()標頭或使用getInputStream()檢索內容之前,您需要通過調用以下內容與URL資源建立實際連接:

URL url = new URL("http", ipToPoll, "/"); // -1 removed; assuming port = 80 always
// check your device html page address; change "/" to "/index.html" if required

URLConnection con = url.openConnection();

// set connection properties
con.setConnectTimeout(1000);
con.setReadTimeout(1000);

// establish connection
con.connect();

// get "content-type" header
Pattern p = Pattern.compile("text/html;\\s+charset=([^\\s]+)\\s*");
Matcher m = p.matcher(con.getContentType());

當您首先調用openConnection() (它提示錯誤,但是)它沒有建立任何連接。 它只是為您提供URLConnection的實例,讓您使用setConnecTimeout()指定連接屬性,例如連接超時。

如果您發現這很難理解,可能會有助於您了解它類似於創建一個new File() ,該new File()僅表示一個File但是不會創建一個File (假設它不存在),除非您繼續進行調用File.createNewFile() (或將其傳遞給FileReader )。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM