What is the URL.getAuthority() method in Java?

The getAuthority() method of the URL class can be used to get the authority part of a URL object. The authority part of a URL object refers to the hostname with the port of the URL.

The URL class is present in the java.net package.

Syntax

The syntax of the getAuthority() method is as follows:

public String getAuthority()

This method doesn’t take any argument. The return type of the getAuthority() method is String.

Note: The getAuthority() method returns the hostname with the port of the URL, whereas the getHost() method only returns the hostname.

Code

The code below demonstrates how to use the getAuthority() method:

import java.net.URL;
class GetAuthorityExample {
public static void main( String args[] ) {
try {
URL url= new URL("https:// www.educative.io:8000");
String authority = url.getAuthority();
System.out.println("The URL is : "+url);
System.out.println("Authority is : "+ authority);
} catch (Exception e) {
System.out.println(e);
}
}
}

Explanation

In the code above:

  • In line 6, we create an URL object.
URL url= new URL("https:// www.educative.io:8000");
  • In line 7, we use the getAuthority() method to get the authority part of the URL object.
String authority =url.getAuthority();
  • In lines 8 and 9, we print the URL and the authority of the URL.

Free Resources