«Back to Home

Core Java

Topics

URLConnection Class In Java

URLConnection Class
 
In Java, the URLConnection class shows a communication link between the URL and the Application. It can be used to read and write the data to the particular resource, referred by the URL.
 
Get the object of URLConnection class

The URL class openConnection() method is used to return the object of URLConnection class.
 
Syntax

public URLConnection openConnection()throws IOException{}
 
Display source code of a webpage by URLConnecton class

The URLConnection class gives many methods. We can show all the data of a Webpage, using the getInputStream() method. The getInputStream() method is used to return all the data of the particular URL in the stream, which can be read and displayed.
 
Let’s see an example of URLConnection class, given below.
 
Code
  1. import java.io.*;  
  2. import java.net.*;  
  3. public class URLConnectionClass {  
  4.     public static void main(String[] args) {  
  5.         try {  
  6.             URL u = new URL("http://www.google.com/images");  
  7.             URLConnection uc = u.openConnection();  
  8.             InputStream is = uc.getInputStream();  
  9.             int i;  
  10.             while ((i = is.read()) != -1) {  
  11.                 System.out.print((char) i);  
  12.             }  
  13.         } catch (Exception e) {  
  14.             System.out.println(e);  
  15.         }  
  16.     }  
  17. }  
8

Summary

Thus, we learnt Java URLConnection class shows a communication link between the URL, the Application and it can be used to read and write the data to the particular resource, referred by the URL and also learnt how we can use it in Java.