Introduction
In this article, we discuss the URL and URLConnection classes in Java.
What is the URL?
It takes the form of a string that describes how to find a resource on the Internet. URLs have two main components: the protocol needed to access the resource and the location of the resource. This class represents an URL. It is an acronym for Uniform Resource Locator. It points to or determines a resource on the World Wide Web. For example:
The following figure shows the URL. It is the web address that we have typed into a browser like http://www.google.com/.

An URL contains many pieces of information.
Protocol - In this case, HTTP is the protocol.
Server name or IP Address - In this case, www.c-sharpcorner.com is the server name.
Port Number - It is an optional attribute, If we write http://www.c-sharpcorner.com:90/authors/fd0172/, 90 is the port number.
File name or directory name - In this case, /authors/fd0172/sandeep-sharma.aspx is the file name.
Some commonly used public methods of the URL class are:
| String getProtocol |
it returns the protocol of the URL. |
| String getHost |
It returns the hostname of the URL. |
| String getPort() |
it returns the Port Number of the URL. |
| String getFile() |
returns the file name of the URL. |
Example
This example displays the Protocol, Host name, Port number and File name of a given URL:
- //URLDEMO.java
- import java.io.*;
- import java.net.*;
- public class URLEx
- {
- public static void main(String[] args)
- {
- try
- {
- URL u = new URL("http://www.c-sharpcorner.com/authors/fd0172/sandeep-sharma.aspx");
- System.out.println("Protocol: " + u.getProtocol());
- System.out.println("Port Number: " + u.getPort());
- System.out.println("File Name: " + u.getFile());
- System.out.println("Host Name: " + u.getHost());
- } catch (Exception ex)
- {
- System.out.println(ex);
- }
- }
- }


PRAGASH YADHAVPosted Jul 3, 2015, 12:13 AM
thanks sir
Sandeep SharmaPosted Jun 13, 2013, 5:55 AM
Thanks sir for defining the standard that specifies about an URL.
Sam HobbsPosted Jun 12, 2013, 7:38 PM
RFC 1738 is the standard that specifies what an URL is. The standard actually just says that the format of an URL is "scheme:scheme-specific-part" where the scheme is the protocol. The scheme-specific-part depends on the protocol. For HTTP the format of the scheme-specific-part is "//host:port/path?searchpart".