Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java | API to get protocol://domain.port from URL

Tags:

java

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.

like image 529
Rupesh Avatar asked Aug 20 '15 09:08

Rupesh


People also ask

How do I find the protocol of a URL?

The getProtocol() function is a part of URL class. The function getProtocol() returns the Protocol of a specified URL.

How to get host and port from URL in java?

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.

How can we get hostname and port information in Javascript?

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.


2 Answers

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);
like image 52
Cardin Avatar answered Oct 09 '22 11:10

Cardin


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);
}
like image 34
mthmulders Avatar answered Oct 09 '22 09:10

mthmulders