What is the URL.getHost method in Java?
The getHost method of the URL class can be used to get the hostname of the URL object.
Syntax
public String getHost()
Parameters
This method doesn’t take any parameters.
Return value
The return type of the getHost method is a String. If the URL contains an IPv6 address instead of a domain name, then this method returns the IPv6 address enclosed in square brackets ([IPV6_address]).
The
URLclass is present in thejava.netpackage.
The
getHostmethod only returns the host name, whereas thegetAuthoritymethod returns the host name with theport number.
Code
The code below demonstrates how to use the getHost method:
import java.net.URL;class GetHostExample {public static void main( String args[] ) {try {URL url= new URL("https:// www.educative.io:8000");String hostName = url.getHost();System.out.println("The URL is : "+url);System.out.println("Host name is : "+ hostName);} catch (Exception e) {System.out.println(e);}}}
Explanation
In the code above,
- In line number 6, we create a
URLobject.
URL url= new URL("https:// www.educative.io:8000");
- In line number 7, we use the
getHostmethod to get the host name of theURLobject.
String hostName =url.getHost();
- In lines 8 and 9, we print the
URLand the host name of theURL.