Tuesday, December 6, 2011

Android Getting HTML from Webpages

Before you can access the internet you must enable internet access, add the line below to your AndroidManifest.xml file (I added mine under the minSdkVersion entry)
<uses-permission android:name="android.permission.INTERNET"/>
Now you can add this function to get the HTML of a website..
1:  public String getHTML(String urlToRead) {  
2:    URL url;  
3:    HttpURLConnection conn;  
4:    BufferedReader rd;  
5:    String line;  
6:    String result = "";  
7:    try {  
8:      url = new URL(urlToRead);  
9:      conn = (HttpURLConnection) url.openConnection();  
10:      conn.setRequestMethod("GET");  
11:      rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));  
12:      while ((line = rd.readLine()) != null) {  
13:       result += line;  
14:      }  
15:      rd.close();  
16:    } catch (Exception e) {  
17:      Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();  
18:    }  
19:    return result;  
20:   }  
And example usage..
String s = getHTML("http://lerietaylor.com/");       
Toast.makeText(getApplicationContext(), s, Toast.LENGTH_LONG).show();