13

I have got URL as referrer and want to get protocol and domain from it.

For example: If URL is https://test.domain.com/a/b/c.html?test=hello then output needs to be https://test.domain.com. I have gone through http://docs.oracle.com/javase/7/docs/api/java/net/URI.html and I can't seems to find any method that can directly do so.


I am not using Spring, so can't use Sprint classes (if any).


Guys I can write custom login to get port, domain and protocol from URL, but looking for API which already has this implemented and can minimize my time in testing various scenarios.

Rupesh
  • 2,627
  • 1
  • 28
  • 42

3 Answers3

22

To elaborate on what @Rupesh mentioned in @mthmulders answer,

getAuthority() gives both domain and port. So you just concatenate it with getProtocol() as prefix:

URL url = new URL("https://test.domain.com/a/b/c.html?test=hello");
String protocol = url.getProtocol();
String authority = url.getAuthority();
return String.format("%s://%s", protocol, authority);
Cardin
  • 5,148
  • 5
  • 36
  • 37
  • If someone like me just want the URL without host name and port then use `url.getPath()` – Kapil Jan 20 '20 at 10:21
14

Create a new URL object using your String value and call getHost() or any other method on it, like so:

URL url = new URL("https://test.domain.com/a/b/c.html?test=hello");
String protocol = url.getProtocol();
String host = url.getHost();
int port = url.getPort();

// if the port is not explicitly specified in the input, it will be -1.
if (port == -1) {
    return String.format("%s://%s", protocol, host);
} else {
    return String.format("%s://%s:%d", protocol, host, port);
}
user987339
  • 10,519
  • 8
  • 40
  • 45
mthmulders
  • 9,483
  • 4
  • 37
  • 54
-1

getAuthority() returns the host along with the port but getHost() returns only the host name. So if URL is "https://www.hello.world.com:80/x/y/z.html?test=hello", then getAuthority() return www.hello.world.com:80 while getHost() returns www.hello.world.com

Example

URL url = new URL("https://www.hello.world.com:80/x/y/z.html?test=hello");
String protocol = url.getProtocol();
String host = url.getHost();
int port = url.getPort();
String authority = url.getAuthority();

System.out.println("Host "+host);   // www.hello.world.com
System.out.println("authority "+authority);   // www.hello.world.com:80

//Determining Protocol plus host plus port (if any) url using Authority (simple single line step)
System.out.println("ProtocolHostPortURL:: "+ String.format("%s://%s", protocol, authority));

//Determining Protocol plus host plus port (if any) url using Authority (multi line step)
//If the port is not explicitly specified in the input, it will be -1.
if (port == -1) {
    System.out.println("ProtocolHostURL1:: "+ String.format("%s://%s", protocol, host));        
} else {
    System.out.println("ProtocolHostPortURL2:: "+ String.format("%s://%s:%d", protocol, host, port));    
}
vinsinraw
  • 2,003
  • 1
  • 16
  • 18