Working with URL in Java (URL Processing)

by | Dec 20, 2020 | Java

Home » Java » Working with URL in Java (URL Processing)

Working with URL in Java

URL stands for Uniform Resource Locator. Every webpage or resource on the Internet has a unique URL by which it is recognized. If you want to develop a web-based application, your program needs to be able to interact with URLs as well as manipulate if required.

Components of an URL

A general form of an URL is as follows: protocol://host:port/path?query#ref

Commonly used protocols are HTTP, HTTPS, FTP, and File. The host is called the authority. Ports are channels from where data packets are sent and received. If a port is not mentioned, the default PORT 80 is used in the case of HTTP.

Constructors

All methods used to work with URLs can be found in the java.net.URL class. The constructors are as follows:

  • public URL (String protocol, String host, int port, String file) throws MalformedURLException
  • public URL (String protocol, String host, String file) throws MalformedURLException
  • public URL (String url) throws MalformedURLException
  • public URL (URL context, String url) throws MalformedURLException

Methods

MethodDescription
Public String getPath()Returns the path of the URL
Public String getQuery()Returns the query of the URL
Public String getAuthority()Returns the authority
Public int getPort()Returns the Port number
Public int getDefaultPort()Returns the default Port number
Public String getHost()Returns the host
Public String getFile()Returns the name of the file

 

Example

This example will put to use some of the methods mentioned above on a working URL.

import java.net.*;
import java.io.*;
public class SampleURL {
public static void main (String [] args)
{
try {
URL url = mew URL (“https://www.wikipedia.org/”);
System.out.println("URL is " + url.toString());
System.out.println("protocol is " + url.getProtocol());
System.out.println("authority is " + url.getAuthority());
System.out.println("file name is " + url.getFile());
System.out.println("host is " + url.getHost());
System.out.println("path is " + url.getPath());
System.out.println("port is " + url.getPort());
System.out.println("default port is " + url.getDefaultPort());
System.out.println("query is " + url.getQuery());
System.out.println("ref is " + url.getRef());
}
catch (IO Exception e) {
e.printStackTrace();
}
}
}

 

Author

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Author