zoukankan      html  css  js  c++  java
  • Java基于url获取host的两种方法(转载)

    https://my.oschina.net/u/195065/blog/190747

    需求:

    基于url获取host,case如下:

    http://snv.iteye.com/blog/1992991结果为snv.iteye.com

    snv.iteye.com/blog/1992991结果为snv.iteye.com

    https://snv.iteye.com/blog/1992991结果为snv.iteye.com

    http://snv.iteye.html结果为“”

    http://snv.iteye.htm结果为“”

    snv.iteye.html结果为“”

    teye.html结果为“”

    http://www.iteye.com/blog/1992991结果为www.iteye.com

    www.iteye.com/blog/1992991结果为www.iteye.com

    https://www.iteye.com/blog/1992991结果为www.iteye.com

    方法实现如下:

    方法1:基于URI或者URL

    依赖:

    Xml代码   收藏代码
    1. <dependency>  
    2.     <groupId>commons-lang</groupId>  
    3.     <artifactId>commons-lang</artifactId>  
    4.     <version>2.6</version>  
    5. </dependency>  

    代码:

    Java代码   收藏代码
    1. private static String getHost(String url) {  
    2.     if (!(StringUtils.startsWithIgnoreCase(url, "http://") || StringUtils  
    3.             .startsWithIgnoreCase(url, "https://"))) {  
    4.         url = "http://" + url;  
    5.     }  
    6.     String returnVal = StringUtils.EMPTY;  
    7.     try {  
    8.         URI uri = new URI(url);  
    9.         returnVal = uri.getHost();  
    10.     } catch (Exception e) {  
    11.     }  
    12.     if ((StringUtils.endsWithIgnoreCase(returnVal, ".html") || StringUtils  
    13.             .endsWithIgnoreCase(returnVal, ".htm"))) {  
    14.         returnVal = StringUtils.EMPTY;  
    15.     }  
    16.     return returnVal;  
    17. }  

    方法2:基于正则

    依赖:

    Xml代码   收藏代码
    1. <dependency>  
    2.     <groupId>commons-lang</groupId>  
    3.     <artifactId>commons-lang</artifactId>  
    4.     <version>2.6</version>  
    5. </dependency>  

    代码:

    Java代码   收藏代码
    1. public static String getHost(String url) {  
    2.     if (!(StringUtils.startsWithIgnoreCase(url, "http://") || StringUtils  
    3.             .startsWithIgnoreCase(url, "https://"))) {  
    4.         url = "http://" + url;  
    5.     }  
    6.   
    7.     String returnVal = StringUtils.EMPTY;  
    8.     try {  
    9.         Pattern p = Pattern.compile("(?<=//|)((\w)+\.)+\w+");  
    10.         Matcher m = p.matcher(url);  
    11.         if (m.find()) {  
    12.             returnVal = m.group();  
    13.         }  
    14.   
    15.     } catch (Exception e) {  
    16.     }  
    17.     if ((StringUtils.endsWithIgnoreCase(returnVal, ".html") || StringUtils  
    18.             .endsWithIgnoreCase(returnVal, ".htm"))) {  
    19.         returnVal = StringUtils.EMPTY;  
    20.     }  
    21.     return returnVal;  
    22. }  
  • 相关阅读:
    文件
    drf序列化组件
    drf入门规范
    单例模式
    初识drf
    restful规范
    虚拟环境使用
    vue基础(三)
    vue基础(二)
    作业
  • 原文地址:https://www.cnblogs.com/lzh1043060917/p/13899175.html
Copyright © 2011-2022 走看看