Free Data Structures and Algorithms Course

Subscribe below and get all best seller courses for free !!!


Subscribe to all free courses

How to read source of a Url using API ?.

Program to demonstrate how to read page source of a Url using API.

package com.hubberspot.code;


public class ReadUrlDemo {

 public static void main(String[] args) {
  try {

   // Create a URL object by providing URL in the form of String.
   URL url = new URL("");

   try {

    // Creating a BufferedReader object for reading the
    // contents of URL by passing an object of InputStreamReader.
    // URL object created above has a method called as openStream()
    // This method opens a connection to the url passed and returns 
    // an InputStream for reading from that connection.
    BufferedReader in = new BufferedReader(
      new InputStreamReader(

    // Creating a String object to store the contents of url line 
    // by line
    String output;

    // BufferedReader has a method called as readLine() reads a 
    // line of text. A line is terminated by line feed ('\n') 
    // a carriage return ('\r'). It returns a null is nothing is read 
    // Applying a while based on the condition till the readline method
    // returns something.
    // Finally printing on the console.
    while ((output = in.readLine()) != null) {

    // Closing BufferedReader by close method ... very important for
    // resource management
   } catch (IOException ex) {
  } catch (MalformedURLException ex) {

Output of the program : 

© 2021 Learn Java by Examples Template by Hubberspot