Downloading a web page using URL and URLConnection classes

This Java code example shows how to download a webpage into a StringBuilder instance using the and classes.
First we create an URL object specifying the url for the page as argument. URLConnection is an abstract class and cannot be instantiated so we need to call its static method openConnection()
to get an instance of it. Now the connection to the web page is open and we can start reading data from it.

To do that we call getInputStream on the URLConnection object and use it as an argument to our BufferedInputStream.
One byte at a time is read until we reach the end of the stream (when -1 is returned from the read() method), and every byte is casted to datatype char and appended to a StringBuilder instance.
Instead of reading data one byte at a time we could read data into a buffer which could be more efficient.
Finally we print out the contents of the page and the size of it.

Search for more Java info on this site here:
Custom Search

Please type any questions here.