Home
Blog
Software
Contact
Mailing List
IPhone Products
SMS To Gmail
Voicemail To Gmail
Calls To Calendar
Other Products
TiffWizard
Sites
SaveMySerials
How Long For Me
DocuTerminal
Blog
Twitter
|
<< Back To All Blogs
Fetching web pages and web data as a string in Google Android
Sunday, January 4th, 2009
I have been battling with a seemingly easy task of fetching a website as a string today in Android and surprisingly it is not as easy as one might think.
My first issue, which was not returning a SecurityException as I had read it would, was the permissions issue. Android has a very strict (this is a good thing) permissions structure, in which you must request permission in your application to access all hardware features, and most user-specific data on the device. I had forgotten to poll Android for permissions to android.permission.INTERNET. As you can probably imagine, this grants access to use the device's internet (as well as sockets) and I was getting an exception thrown as "unknown error". First problem resolved.
My second issue was that I could not find an easy way to fetch a web site, such as I was used to doing in .NET with a simple WebClient. So without further explanation, here is how you fetch a website in Android, get the data as a stream, and return that stream as a string:
String myUrl = "http://www.nerdyhearn.com";
URL url = new URL(myUrl);
URLConnection uconn = url.openConnection();
HttpURLConnection conn = (HttpURLConnection)uconn;
conn.connect();
Object content = conn.getContent();
java.io.InputStream stream = (java.io.InputStream)content;
java.io.DataInputStream din = new java.io.DataInputStream(stream);
StringBuffer sb = new StringBuffer();
String line = null;
while((line=din.readLine()) != null){
sb.append(line+"n");
}
The final string will be available in sb.toString().
I would have thought that these days fetching a page shouldn't have been so cast-tastic and convoluted just to get the data from a website... but then again who thinks these days anyways.
Web Fetchin' Tom Out.
Tags
Android
Related Blogs
No More IPhone for Me
My first Android complaint
Configuring the Android Dev Phone 1 for ATT/Cingular
2 Android Apps worth looking at
Comments
Currently no comments.
Add A Comment
Name:
URL:
Email Address: (not public, used to send notifications on further comments)
Comments:

Enter the text above, except for the 1st and last character:
|