Java | API to get protocol://domain.port from URL
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);
}
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);