I am trying to get the HTML source from a URL in my Android app using the code below. However, it crashes at the line HttpResponse response = client.execute(request);
. How can I fix this?
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
HttpResponse response = client.execute(request);
String html = "";
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null)
{
str.append(line);
}
in.close();
html = str.toString();
UPDATE! I am too new of a user to post my own official answer apparently, so here it is:
Thanks to both of you! Hichris' comments & links pointed me in the right direction. Here are the 3 hurdles that were causing the problem:
- The
AsyncTask
should be placed in the same class file, but as a sub-class (I might not have my terminology right there) - I was filling a text box with the resulting html code. However, I was doing that within the
doInBackground()
section of theAsyncTask
when I should have been doing it inonPostExecute()
. - The urls I was passing to the
AsyncTask
were not properly converted toURI
. This caused the program to crash for some urls but not others.