0

I need to convert a list of URLS to their host name. SO tried the below mentioned code:

URL netUrl = new URL(url); 
String host = netUrl.getHost();

The above mentioned code is producing output as shown below:

a95-101-128-242.deploy.akamaitechnologies.com
a23-1-242-192.deploy.static.akamaitechnologies.com
edge-video-shv-01-lht6.fbcdn.net

I want only the website name from the above output like as shown below:

akamaitechnologies
akamaitechnologies
fbcdn

Please someone help. Thanks

priyanka Dhiman
  • 95
  • 3
  • 11

1 Answers1

0

If you want to parse a URL, use java.net.URI. java.net.URL has a bunch of problems -- its equals method does a DNS lookup which means code using it can be vulnerable to denial of service attacks when used with untrusted inputs.

public static String getDomainName(String url) throws URISyntaxException {
  URI uri = new URI(url);
  String domain = uri.getHost();
  return domain.startsWith("www.") ? domain.substring(4) : domain;
}

This should work.

Fotis Grigorakis
  • 363
  • 1
  • 3
  • 16
  • its returning same result like a95-101-128-242.deploy.akamaitechnologies.com – priyanka Dhiman Jul 25 '17 at 10:37
  • Yes, because you should replace this code: `domain.startsWith("www.")` with something that suits better for you! As far i can see your domains names are not starting with `www`. So change it and you should be ok. – Fotis Grigorakis Jul 25 '17 at 10:39
  • You should have a look on this question: https://stackoverflow.com/questions/9607903/get-domain-name-from-given-url – Fotis Grigorakis Jul 25 '17 at 11:08