Java基于url获取host的两种方法

需求:

基于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. }  

转载于:https://my.oschina.net/u/195065/blog/190747

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值