【问题标题】:Java | API to get protocol://domain.port from URL爪哇 |从 URL 获取协议://domain.port 的 API
【发布时间】:2015-11-13 20:29:48
【问题描述】:

我有一个 URL 作为引用者,想从中获取协议和域。

例如:如果 URL 是 https://test.domain.com/a/b/c.html?test=hello,那么输出需要是 https://test.domain.com。我已经通过http://docs.oracle.com/javase/7/docs/api/java/net/URI.html 似乎找不到任何可以直接这样做的方法。


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


伙计们,我可以编写自定义登录以从 URL 获取端口、域和协议,但正在寻找已经实现此功能的 API,并且可以最大限度地减少我测试各种场景的时间。

【问题讨论】:

标签: java


【解决方案1】:

详细说明@Rupesh 在@mthmulders 回答中提到的内容,

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);

【讨论】:

  • 为我工作。为 getAuthority() +1。
  • 如果像我这样的人只想要没有主机名和端口的 URL,请使用 url.getPath()
  • 回复较晚,但这是更好的答案
【解决方案2】:

使用您的String 值创建一个新的URL 对象并调用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);
}

【讨论】:

  • 如果 url 是 https://test.domain.com:80/a/b/c.html?test=hello,这将不起作用,输出应该是 https://test.domain.com:80。我可以编写这些逻辑,但要寻找久经考验的 API
  • 不需要端口检查,getAuthority给出域和端口
  • 你必须改变if条件:if (port == -1)
  • 为我工作。但我更喜欢 getAuthority() 而不是这种多行方法,它在单行中完成相同的工作。
【解决方案3】:

getAuthority() 返回主机和端口,但 getHost() 只返回主机名。所以如果 URL 是“https://www.hello.world.com:80/x/y/z.html?test=hello”,那么 getAuthority() 返回 www.hello.world.com:80 而 getHost() 返回 www.hello.world.com

示例

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));    
}

【讨论】:

    猜你喜欢
    • 2017-08-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-26
    • 2012-03-06
    • 2011-10-19
    相关资源
    最近更新 更多