当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java URI getHost()用法及代码示例


getHost()函数是URI类的一部分。函数getHost()返回指定URI的主机。
URL的主机部分是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


相关用法


注:本文由纯净天空筛选整理自andrew1234大神的英文原创作品 URI getHost() method in Java with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。