Dato un URL, voglio estrarre il nome di dominio (non dovrebbe includere la parte 'www'). L'URL può contenere http / https. Ecco il codice java che ho scritto. Anche se sembra funzionare bene, c'è qualche approccio migliore o ci sono alcuni casi limite, che potrebbero fallire.
public static String getDomainName(String url) throws MalformedURLException{
if(!url.startsWith("http") && !url.startsWith("https")){
url = "http://" + url;
}
URL netUrl = new URL(url);
String host = netUrl.getHost();
if(host.startsWith("www")){
host = host.substring("www".length()+1);
}
return host;
}
Input: http://google.com/blah
Uscita: google.com
http://www.de/o http://www.com/non darà i risultati desiderati.
http://74.125.226.70e fammi sapere come funziona :)