2011-03-26 87 views
0

如何連接到網站並將HTML抓取到字符串中?我想在我的應用程序的幕後執行此操作。我想在以後的屏幕中解析這些信息。獲取HTML爲字符串

回答

3

作爲起點,檢查RIM documentation on HttpConnection(滾動到「使用HttpConnection的示例」)。

該示例將響應作爲字節數組讀取,但如果您在Java SE中正常工作,則可以輕鬆更改它以讀取字符串。另一點是使用適當的傳輸(BIS,BES,TCP,WiFi等 - 它應該可以在特定設備上使用)。對於運輸檢測,您可以檢查this

+0

也不是,「新的字符串(byte [])」是字節數組的選項 - 讓你更加靈活,因爲byte []可以是一個非常實用的數據結構 – Dan 2011-03-27 15:06:43

+0

@Arhimed - 如何改變它到一個字符串? – Christopher 2012-11-15 18:20:40

+1

@Christopher:最簡單的方法是通過'new String(byte [] data)'或'new String(byte [] data,String encoding)''。 – 2012-11-15 20:23:35

0
public static String getContentsFrom(String urlString) throws IOException { 
    URL url = new URL(urlString); 
    BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); 
    String inputLine; 
    String content = ""; 
    while ((inputLine = in.readLine()) != null) { 
     content += inputLine; 
    } 
    in.close(); 
    return content; 
} 
+2

不支持java.net.URL。 – hfitzwater 2011-03-26 13:54:22

+1

BufferedReader – 2011-03-26 23:39:07