URL class in java

The Java URL class represents a pointer to a "resource" on the World Wide Web . URL is an acronym for Uniform Resource Locator.

  A resource can be something as simple as a file or a directory, or it can be a reference to a more complicated object, such as a query to a database or to a search engine.


What is a URL?

URL is a string of text that identifies all the resources on Internet, telling us the address of the resource, how to communicate with it and retrieve something from it.
A URL contains many information:

  Protocol : In this case, http is the protocol .

  Server name or IP Address: In this case, www.onlyjavatech.com is the server name.

  Port Number: Port Number is optional. for HTTP services port number is 80. If the port number is not set explicitly then it returns -1.

  File Name or directory name or resource: In this case, URL-class-in-java is the resource name.

Commonly used constructor of URL class

Constructor Description
public URL(String str) Creates a URL object from the String str representation.
public URL(String protocol, String host, int port, String file) Creates a URL object from the specified protocol, host, port number, and file.

Commonly used methods of URL class.

The java.net.URL class provides many methods. The important methods of URL class are given below.

Method Description
public String getFile() Gets the file name of this URL.
public String getHost() Gets the host name of this URL, if applicable.
public String getPort() Gets the port number of this URL.
public String getProtocol() Gets the protocol name of this URL
public toString() Constructs a string representation of this URL.
public URLConnection openConnection() Returns the instance of URLConnection i.e. associated with this URL.
Program to get the information of URL entered by the user.

import java.io.*;
import java.net.*;

class GetURL {
	public static void main(String[] args) throws Exception, IOException {
		System.out.println("Enter url :");
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		String str = br.readLine();

		// create java.net.URL object and pass str
		URL url = new URL(str);
		String host = url.getHost();
		int port = url.getPort();
		String file = url.getFile();
		String prot = url.getProtocol();

		// print all the information
		System.out.println("Host :" + host);
		System.out.println("Port :" + port);
		System.out.println("File/Resource :" + file);
		System.out.println("Protocol :" + prot);
	}
}
Enter url :
https://www.onlyjavatech.com/URL-class-in-java
Host :www.onlyjavatech.com
Port :-1
File/Resource :/URL-class-in-java
Protocol :https