dcsimg
LinkedIn
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Jul 6, 2021

How to Read Data from a URL in Java

Welcome to another Java programming tutorial. This go around we will teach developers how to use the java.net and java.io packages to and APIs to read data from a URL. Java has several APIs and methods that support working with URLs. Below is a code example showing how to read data from a URL:

This code starts out by importing the java.net and java.io packages. Then we create a class that reads the HTML contents from a given URL and outputs them to a console.

*/

import java.net.*;
import java.io.*;

public class ReadingDataFromURL {
	
	public static void main(String[] args) 
	{  
		ReadingDataFromURL readingDataFromURL = new ReadingDataFromURL();
		readingDataFromURL.proceed();
	}

	private void proceed()  
	{
		try 
		{
			String websiteURL = "http://devx.com";
			URL url = new URL(websiteURL);
			URLConnection urlConnection = url.openConnection();
			urlConnection.connect();
			
			BufferedReader bufferedReader = new BufferedReader(
												new InputStreamReader(
												urlConnection.getInputStream()
												)
												);
			String readInputFromLine;
			while ((readInputFromLine = bufferedReader.readLine()) != null) 
				System.out.println(readInputFromLine);
			
			bufferedReader.close();
		} 
		catch (Exception exception) 
		{ 
			System.out.println("Exception: " + exception);
		} 
	}
}

/*

Note: if you change the URL being seached, the output you receive will be different. Try out different URLs to see some different results. For now, you can expect the following output from running this Java code:

[root@mypc]# java CopyOnWriteArrayListEx
301 Moved Permanently

Moved Permanently

The document has moved here.

MS Sridhar
 
Close Icon
Thanks for your registration, follow us on our social networks to keep up-to-date