How to read a webpage contents from a given URL in Java

Reading data from URL (webpage, file etc.) in Java is very easy. Some time ago we have shown you how to download a file that can be reach by an URL – Java download file. Today we will show you how to read a webpage contents from a given URL. Here is the code.

Java read URL to String



public class ReadFromURLExample {

	public static void main(String[] args) {
		try {
			URL url = new URL("");
			InputStream is = url.openStream();
			BufferedReader br = new BufferedReader(new InputStreamReader(is));
			String line;
			while ( (line = br.readLine()) != null)
		} catch (Exception e) {

As an output of this code execution you will get the HTML code of the main page.

Download this sample code here.

This code is available on our GitHub repository as well.

2 Responses to "How to read a webpage contents from a given URL in Java"

  1. Haseeb says:

    good post i will try to use it in my smaal future project


Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>