Java | 从URL获取protocol://domain.port的API

Rup*_*esh 7 java

我有URL作为引荐来源网址,并希望从中获取协议和域。

例如:如果https://test.domain.com/a/b/c.html?test=hello输出URL,则输出必须为https://test.domain.com。我已经经历了http://docs.oracle.com/javase/7/docs/api/java/net/URI.html,但似乎找不到任何可以直接这样做的方法。


我没有使用Spring,所以不能使用Sprint类(如果有)。


伙计们,我可以编写自定义登录名以从URL获取端口,域和协议,但是正在寻找已经实现此功能的API,可以将我在各种情况下的测试时间降至最低。

mth*_*ers 7

URL使用您的String值创建一个新对象并调用getHost()或对其上的任何其他方法,如下所示:

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);
}
Run Code Online (Sandbox Code Playgroud)


Car*_*din 6

要详细说明@mthmulders回答中的@Rupesh,

getAuthority()提供域和端口。因此,您只需将其getProtocol()作为前缀串联即可:

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);
Run Code Online (Sandbox Code Playgroud)