get domain name from url using java

Yesterday, I encountered a small problem in the development. It was not worth writing, but I haven’t written an article recently. I decided to write it simply to refresh the sense of existence.

There is a requirement to get the complete domain name from the url. I found it on the Internet, and most of it is the following article:

https://blog.csdn.net/u013217757/article/details/53838250/

I tested it and it works perfectly. It is mainly the following code:

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

Ordinary urls are normal, but something went wrong after running for a few days. If "_" (underscore) or "-" (minus sign) appears in the domain name, the URI is empty.

Checked the document, it is probably described like this:

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.

My English is very bad. After reading it roughly, it means that underscores and minus signs are legal. But when I get it, I will report an error... Speechless. I didn't have time to continue searching, and suddenly thought that URIs can't work, so can URL objects? Try it now:

	public static String getDomainName(String url) {
		String host = "";
		try {
			URL Url = new URL(url);
			host = Url.getHost();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return host;
	}

Sure enough. Use it like this first. I don't know if there will be other problems. Please refer carefully to the great gods.

Guess you like

Origin blog.csdn.net/ziele_008/article/details/106275703