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.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代码- <dependency>
- <groupId>commons-lang</groupId>
- <artifactId>commons-lang</artifactId>
- <version>2.6</version>
- </dependency>
代码:
Java代码- private static String getHost(String url) {
- if (!(StringUtils.startsWithIgnoreCase(url, "http://") || StringUtils
- .startsWithIgnoreCase(url, "https://"))) {
- url = "http://" + url;
- }
- String returnVal = StringUtils.EMPTY;
- try {
- URI uri = new URI(url);
- returnVal = uri.getHost();
- } catch (Exception e) {
- }
- if ((StringUtils.endsWithIgnoreCase(returnVal, ".html") || StringUtils
- .endsWithIgnoreCase(returnVal, ".htm"))) {
- returnVal = StringUtils.EMPTY;
- }
- return returnVal;
- }
方法2:基于正则
依赖:
Xml代码- <dependency>
- <groupId>commons-lang</groupId>
- <artifactId>commons-lang</artifactId>
- <version>2.6</version>
- </dependency>
代码:
Java代码- public static String getHost(String url) {
- if (!(StringUtils.startsWithIgnoreCase(url, "http://") || StringUtils
- .startsWithIgnoreCase(url, "https://"))) {
- url = "http://" + url;
- }
- String returnVal = StringUtils.EMPTY;
- try {
- Pattern p = Pattern.compile("(?<=//|)((\\w)+\\.)+\\w+");
- Matcher m = p.matcher(url);
- if (m.find()) {
- returnVal = m.group();
- }
- } catch (Exception e) {
- }
- if ((StringUtils.endsWithIgnoreCase(returnVal, ".html") || StringUtils
- .endsWithIgnoreCase(returnVal, ".htm"))) {
- returnVal = StringUtils.EMPTY;
- }
- return returnVal;
- }
标签:iteye,Java,url,snv,host,returnVal,com,StringUtils 来源: https://www.cnblogs.com/lzh1043060917/p/13899175.html