0

I want to get the HTML from a website, for that I'm using this code. When I try to add this code from the documentation I get this error:

            //Get HTML
            URL url = new URL("http://www.android.com/");
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            try {
                InputStream in = new BufferedInputStream(urlConnection.getInputStream());
                readStream(in);
                finally {
                    urlConnection.disconnect();
                }
            }

What went wrong? Did I forget to import some stuff?

Jan Koekepan
  • 81
  • 1
  • 9

3 Answers3

1

You didn't forget to import anything.

There's a couple things wrong with the code.

1) You're missing the catch block to go along with try and your finally statement is incorrectly inside the if. It should look like the follow:

try {
    InputStream in = new BufferedInputStream(urlConnection.getInputStream());
    readStream(in);
} catch (Exception e) { // best practice is to be more specific with the Exception type
    urlConnection.disconnect();
    Log.w("Login", "Error downloading HTML from " + url);        
} finally {
    if(urlConnection != null) {
                urlConnection.disconnect();
    }
}

2) In that example you are following in the documentation, they are leaving it up to you to decide what to do with the stream once it it retrieved from the urlConnection.

So create your own void readStream(InputStream in) method in your activity which can then consume the InputStream. Write it to disk, display it on screen, its up to you.

Jon Finerty
  • 198
  • 1
  • 8
0

You are missing the catch clause. Put this before your finally clause as such:

} catch (Exception e) { //it's bad practice to catch Exception, specify it more if you can, i just don't know what errors InputStream throws
    Log.e("ClassTag", e.getMessage(), e);
} finally { /* ... */ }
nbokmans
  • 5,492
  • 4
  • 35
  • 59
0

The finally block does not go inside the try block, change it to:

 try {
     InputStream in = new BufferedInputStream(urlConnection.getInputStream());
     readStream(in);
 }
 finally {
    urlConnection.disconnect();
}

Also make sure that you have imported java.net.URL.

RobVoisey
  • 1,083
  • 15
  • 24