Get domain name from URL in Java/Android

hansottowirtz picture hansottowirtz · Apr 16, 2014 · Viewed 15.6k times · Source

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

peshkira picture peshkira · Apr 16, 2014

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