Program To Read Contents From URL Using URLConnection In Java

LEVEL: Beginner

Whats in this post?

  1. Code
  2. Output
  3. Background and Explanation of the code

Code


To copy code: Click  View Source “View Source” on the right of this code snippet.

Background and Explanation of the code

This program reads the content of the web-page available for given URL. When this standalone program is run from command prompt the main() method will be called.

URL class of java provides a simple, concise API to access information across the Internet using URLs.  To access the actual bits or content information of a URL, you create a URLConnection object from it, using its openConnection( ) method, like this:

URLConnection urlCon = url.openConnection();

Then open input stream to read content from the url connection object.

urlCon.getInputStream();

The while loop reads one by one character from the input stream and print it on the console. Whenever the entire content of the page will be read, input stream will encounter the value -1 so the program-control exist from while loop.

To compile the program from command prompt : javac UrlConnectionDemo.java

To run the program from command prompt: java  UrlConnectionDemo