📜  Java中的 URI getHost() 方法及示例

📅  最后修改于: 2022-05-13 01:55:32.131000             🧑  作者: Mango

Java中的 URI getHost() 方法及示例

getHost()函数是 URI 类的一部分。函数getHost() 返回指定 URI 的主机。
URL 的 Host 部分是 URI 的主机名。

函数签名

public String getHost()

返回类型函数返回字符串类型

句法

url.getHost()

参数:此函数不需要任何参数

以下程序将说明 getHost()函数的使用

示例 1:

// Java program to show the 
// use of the function getHost()
  
import java.net.*;
class Solution {
public static void main(String args[])
    {
        // URI  object
        URI uri = null;
  
        try {
            // create a URI
            uri = new URI("https://www.geeksforgeeks.org");
  
            // get the Host
            String host = uri.getHost();
  
            // display the URI
            System.out.println("URI = " + uri);
  
            // display the Host
            System.out.println("Host = " + host);
        }
        // if any error occurs
        catch (URISyntaxException e) {
            // display the error
            System.out.println("URI Exception =" + e.getMessage());
        }
    }
}
输出:
URI = https://www.geeksforgeeks.org
Host = www.geeksforgeeks.org

示例 2: getAuthority() 和 getHost()函数的区别在于 getAuthority() 将主机连同端口一起返回,而 getHost() 只返回主机名。

// Java program to show the 
// use of the function getHost()
  
import java.net.*;
  
class Solution {
    public static void main(String args[])
    {
        // url  object
        URI uri = null;
  
        try {
            // create a URI
            uri = new URI("https://www.geeksforgeeks.org:80");
  
            // get the Authority
            String authority = uri.getAuthority();
  
            // get the Host
            String host = uri.getHost();
  
            // display the URI
            System.out.println("URI = " + uri);
  
            // display the Authority
            System.out.println("Authority = " + authority);
  
            // display the Host
            System.out.println("Host = " + host);
        }
        // if any error occurs
        catch (URISyntaxException e) {
            // display the error
            System.out.println("URI Exception =" + e.getMessage());
        }
    }
}
输出:
URI = https://www.geeksforgeeks.org:80
Authority = www.geeksforgeeks.org:80
Host = www.geeksforgeeks.org