hansottowirtz hansottowirtz - 4 months ago 30
Java Question

Get domain name from URL in Java/Android

In my app, I need to get the favicon.ico from a URL. (eg. "http://google.com/favicon.ico").
Users can input all kinds of URLs, and I need only the domain name.

Examples:

http://drive.google.com/bla/bla/bla -> drive.google.com

www.facebook.com/lol -> www.facebook.com

192.168.0.1 -> 192.168.0.1 (but not really necessary)


Does anyone have a method to get this?
Thanks!

Answer

Try using something like

String u = "www.facebook.com/lol";
URL url = new URL(u);
String host = url.getHost(); // should be www.facebook.com

If you need different parts of the Url look at the documentation and the other getters here: http://developer.android.com/reference/java/net/URL.html