我需要使用 java.net.url 类的构造函数根据端口号创建一个 URL。为此,我使用了下面的构造函数,public URL(String protocol, String host, int port, String file){}
我需要创建两个不同的 URL;如果端口是 80,需要忽略端口,否则 URL 应该包含端口号。我无法将端口号发送为空,有一个值为 -1。当我使用 -1 作为端口时,它会创建没有端口的 URL。
我的问题是构造函数的文档;构造函数的上方有一个描述,该描述是
“指定 {@code -1} 的 {@code port} 号表示 URL 应使用协议(protocol)的默认端口。”。正如我所提到的,我不想使用默认端口号。如果是这种情况,我怎样才能只用这样的构造函数创建一个 URL?
顺便说一句,我知道,我只能使用字符串版本,我不想写两个新的 URL 来做到这一点。基本上,我想写这样的东西,new URL(scheme, serverName, serverPort == 80 ? -1 : serverPort, contextPath); // as I mentioned based on the documentation of URL constructor, -1 gets the default port number, but in the code it is not like that.
等待您的建议。谢谢你。
编辑 new URL(scheme, serverName, serverPort == 80 ? null: serverPort, contextPath);
最佳答案
我看到文档让您感到困惑。当文档说
Specifying a {@code port} number of {@code -1} indicates that the URL should use the default port for the protocol.
这意味着创建的 URL 没有端口号。但是当你连接到一个主机时,你需要使用一个端口,如果 URL 没有端口,将使用协议(protocol)的默认端口。
关于java - java.net.URL 中 -1 端口值的含义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62792905/