Free Data Structures and Algorithms Course









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










OR



Subscribe to all free courses

How to read source of a Url using java.net API ?.

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

package com.hubberspot.code;

import java.net.MalformedURLException;
import java.net.URL;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

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("http://www.hubberspot.com");

   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(
        url.openStream()));

    // 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) {
     System.out.println(output);
    }

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



Output of the program : 


 
 
© 2021 Learn Java by Examples Template by Hubberspot