1

I used the URL class in Java to retrieve the hostname portion of a URL as follows.

IE, if the URL is https://hostname.mycompany.com, I want the output to just be 'hostname'

URL host = new URL(url);
String hostname = site.getHost().split("\\.")[0];

Is there an easier way to do this? Thanks.

The getHost function returns 'hostname.company.com' instead of 'hostname'

Selina
  • 11
  • 3
  • 2
    IMO, this is a fairly easy way... of course, backward slashes are not used in HTTP, it's about forward slashes. Btw: `toString` should not be necessary. Furthermore, getHost should return the name only - without the protocol... – home Aug 30 '12 at 17:39
  • You could also use a regular expression, but it's essentially doing the same thing. You might also find this interesting: http://stackoverflow.com/questions/288810/get-the-subdomain-from-a-url – mellamokb Aug 30 '12 at 17:40
  • Yep - this is about as easy as it gets. I don't think you need to call `toString` on the result of `getHost()`, though, do you? [It's already a `String`.](http://docs.oracle.com/javase/1.4.2/docs/api/java/net/URL.html#getHost()) – Ry- Aug 30 '12 at 17:41
  • 1
    @home String.split takes a regex. The back-slash is to escape the '.' character to make it a literal dot, otherwise it will match everything. – Alex Aug 30 '12 at 17:43
  • @minitech Thanks, forgot why I called `toString`, it's not needed. – Selina Aug 30 '12 at 17:46
  • @Alex: uhm, of course you're correct, apologies... – home Aug 30 '12 at 17:49
  • @home `getHost` returns everything after the https:// – Selina Aug 30 '12 at 17:53

0 Answers0