URLConnection class is a general purpose class for accessing the attributes of a remote resources.
This class can be used to read and write data to the specified resource referred by the URL.

URLConnection is abstract class which represents communications link between the application and a URL.

The URLConnection object is created by invoking the openConnection() method of URL .

  • Displaying source code of a webpage by URLConnecton class

    The URLConnection class provides many methods, we can display all the data of a webpage by using the getInputStream() method. The getInputStream() method returns all the data of the specified URL in the stream that can be read and displayed.

Example of Java URLConnecton class
import java.io.*;  
import java.net.*;  
public class URLConnectionExample {  
public static void main(String[] args){  
URL url=new URL("http://www.durgeshkumartiwari.info");  
URLConnection urlcon=url.openConnection();  
InputStream stream=urlcon.getInputStream();  
int i;  
}catch(Exception e){System.out.println(e);}  

Example of Java URLConnecton class(Reading all at once)

import java.io.*;
import java.net.*;
public class ReadURLConnection {
	public static void main(String[] args) throws Exception {
		System.out.println("Enter url :");
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		String str = br.readLine();
		URLConnection con = new URL(str).openConnection();
		InputStream is = con.getInputStream();
		byte b[] = new byte[is.available()];
		String content = new String(b);


What next?

Share this page