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

本文介绍了在Java中如何从URL获取hostname的两种方法,包括基于URI或URL的正规方式以及使用正则表达式的解决方案。分别展示了针对不同URL格式的处理,如正确返回hostname或在无效URL时返回空字符串的示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

需求:

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

依赖:

<dependency>
	<groupId>commons-lang</groupId>
	<artifactId>commons-lang</artifactId>
	<version>2.6</version>
</dependency>

代码:

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:基于正则

依赖:

<dependency>
	<groupId>commons-lang</groupId>
	<artifactId>commons-lang</artifactId>
	<version>2.6</version>
</dependency>

代码:

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;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值