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
- import java.io.*;
- import java.net.*;
- public class URLConnectionClass {
- public static void main(String[] args) {
- try {
- URL u = new URL("http://www.google.com/images");
- URLConnection uc = u.openConnection();
- InputStream is = uc.getInputStream();
- int i;
- while ((i = is.read()) != -1) {
- System.out.print((char) i);
- }
- } catch (Exception e) {
- System.out.println(e);
- }
- }
- }
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.