Java URI getHost()方法及示例
getHost() 函数是URL类的一部分。getHost()函数返回一个指定的URL的主机。URL的Host部分是该URL的主机名。主机的格式符合RFC 2732的规定。
函数签名
public String getHost()
语法
url.getHost()
参数 :该函数不需要任何参数。
返回类型 :该函数返回 字符串 类型
下面的程序说明了getHost()函数的使用。
例1 :
// Java program to show the use
// of the function getHost()
import java.net.*;
class GFG {
public static void main(String args[])
{
// url object
URL url = null;
try {
// create a URL
url
= new URL("https:// www.geeksforgeeks.org");
// get the Host
String Host = url.getHost();
// display the URL
System.out.println("URL = " + url);
// display the Host
System.out.println("Host = " + Host);
}
// if any error occurs
catch (Exception e) {
// display the error
System.out.println(e);
}
}
}
输出:
URL = https:// www.geeksforgeeks.org
Host = www.geeksforgeeks.org
例2 :
// Java program to show the
// use of the function getHost()
import java.net.*;
class GFG {
public static void main(String args[])
{
// url object
URL url = null;
try {
// create a URL
url
= new URL(
"https:// www.geeksforgeeks.org:80/url-samefile-method-in-java-with-examples/");
// get the Authority
String authority
= url.getAuthority();
// get the Host
String host = url.getHost();
// display the URL
System.out.println("URL = " + url);
// display the Host
System.out.println("Authority = "
+ authority);
// display the Host
System.out.println("Host = " + host);
}
// if any error occurs
catch (Exception e) {
// display the error
System.out.println(e);
}
}
}
输出:
URL = https:// www.geeksforgeeks.org:80/url-samefile-method-in-java-with-examples/
Authority = www.geeksforgeeks.org:80
Host = www.geeksforgeeks.org
例3: 如果我们创建一个没有主机名的URL,并使用getHost()函数询问主机,该函数返回空白的String。
// Java program to show the
// use of the function getHost()
import java.net.*;
class GFG {
public static void main(String args[])
{
// url object
URL url = null;
try {
// create a URL
url = new URL("https://");
// get the Host
String Host = url.getHost();
// display the URL
System.out.println("URL = " + url);
// display the Host
System.out.println("Host = " + Host);
}
// if any error occurs
catch (Exception e) {
// display the error
System.out.println(e);
}
}
}
输出:
URL = https:
Host =