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.
The getProtocol() function is a part of URL class. The function getProtocol() returns the Protocol of a specified URL.
getHost() method returns the host name of the URL. getPort() method returns the port number of the URL. If the port is not set, then it returns -1. getPath() method returns the path of this URL.
If you only want to return the hostname value (excluding the port number), use the window. location. hostname method instead. This will return a string value containing the hostname and, if the port value is non-empty, a : symbol along with the port number of the URL.
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);
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With