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

package com.itcuties.java;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;

public class ReadFromURLExample {

	public static void main(String[] args) {
		try {
			URL url = new URL("http://www.itcuties.com");
			InputStream is = url.openStream();
			BufferedReader br = new BufferedReader(new InputStreamReader(is));
			
			String line;
			while ( (line = br.readLine()) != null)
				System.out.println(line);
			
			br.close();
			is.close();
			
		} catch (Exception e) {
			e.printStackTrace();
		}	
	}
}

As an output of this code execution you will get the HTML code of the itcuties.com 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

    Reply

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>

Java by Example App is available at Google Play Store NOW