URL stands for Uniform Resource locator

The Java URL class represents an URL

This class is pointer to resource on the world wide web

Lets check with an example

http://166.62.27.173:8090//myurl.html

Here http is the URL

166.62.27.173 is the Server name or IP Address

8090 is the Port Number

Myurl.html is file name

Constructor

URL(String url) – creates URL object from the string Representation

For Example

URL url = new URL(“http://examradar.com”);

Method

Method Description
Public URL Connection openConnection() throws IOException This Method of URL Class returns the object of URL Connection

Lets check the below Syntax

URLConnection urlconn = url.openConnection();

URLConnection

URLConnection is the superclass of all classes of all classes that represents a communication link between the applications and a URL.

Instances of this class can be used both to read from and to write to the resource referenced by the url.

Constructor

URLConnection(URL url) – constructs a URL Connection to the specified url

Methods

Method Description
Public inputStream getInputStream() throws IOException Returns an input stream that reads from this open connection
Public outputStream getOutputStream() throws IOException Returns an output stream that writes to this connection

Example

import java.io.*;

import java.net.*;

public class readDatafromURL{

public static void main(String[] args) throws Exception { 

URL eradar = new URL("http://examradar.com/java-networking-network-basics-socket-overview");

    URLConnection urlconn = eradar.openConnection();

    InputStream stream = urlconn.getInputStream();

    int i;

    while ((i=stream.read())!=-1){

        System.out.println((char)i); 

       }

     }                 

}
Share with : Share on Linkedin Share on Twitter Share on WhatsApp Share on Facebook