使用java从url中获取域名
昨天再开发中遇到个小问题,本来不值得写的,但是最近一直没写文章,决定还是简单写一下,刷刷存在感吧。
有个需求,要从url里面获取出完整的域名。从网上找了一下,大部分都是下面这篇文章:
https://blog.csdn.net/u013217757/article/details/53838250/
我测试了一下,完全没有问题。主要就是下面这段代码:
public static URI getIP(URI uri) {
URI effectiveURI = null;
try {
effectiveURI = new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), null, null, null);
} catch (Throwable var4) {
effectiveURI = null;
}
return effectiveURI;
}
普通url都正常,但是跑了几天后出毛病了,域名里如果出现了“_”(下划线)或者“-”(减号),URI就是空。
查了一下document,大概是这样描述的:
A domain name consisting of one or more labels separated by period characters '.', optionally followed by a period character. Each label consists of alphanum characters as well as hyphen characters '-', though hyphens never occur as the first or last characters in a label. The rightmost label of a domain name consisting of two or more labels, begins with an alpha character.
我英语很烂,看了个大概,反正就是说下划线和减号的合法的。但是获取的时候就是会报错……无语。没工夫继续找了,突然想到URI不行,那URL对象可以么?赶紧试试:
public static String getDomainName(String url) {
String host = "";
try {
URL Url = new URL(url);
host = Url.getHost();
} catch (Exception e) {
e.printStackTrace();
}
return host;
}
果然就可以了。先这样用着吧。不知道会不会有其他问题。请各位大神谨慎参考。