How to get URL content in Java

Reading from a URL is as easy as reading from an input stream. URL is the acronym for Uniform Resource Locator . Java programs that interact with the Internet also may use URLs to find the resources on the Internet they wish to access. Java programs can use a class called URL in the package to represent a URL address . A URL takes the form of a string that describes how to find a resource on the Internet. URLs have two main components: the protocol needed to access the resource and the location of the resource. The easiest way to create a URL object is from a String that represents the human-readable form of the URL address.
URL url = new URL("");

Steps for reading URL Content from webserver:

  1. Create a URL object from the String representation.
  2. Create a new BufferedReader, using a new InputStreamReader with the URL input stream.
  3. Read the text, using readLine() API method of BufferedReader.
import*; import*; public class TestClass { public static void main(String[] args) throws Exception { try{ URL url = new URL(""); BufferedReader reader = new BufferedReader( new InputStreamReader(url.openStream())); String line; while ((line = reader.readLine()) != null) System.out.println(line); reader.close(); }catch(Exception ex){ System.out.println(ex); } } }
When you run the program, you should see the HTML commands and textual content from the HTML file located at "" scrolling by in your command window. Or, you might see the following error message: