如何准确比较 Java 中 URI 对象的端口?

How can I accurately compare ports of URI objects in Java?

这是我的支票。

URI firstURI = new URI("http://example.com:80");
URI secondURI = new URI("http://example.com/testing");


if (!firstURI.getHost().equals(secondURI.getHost()) || 
    !firstURI.getScheme().equals(secondURI.getScheme()) || 
    firstURI.getPort() != secondURI.getPort()) {
        //error
}

默认情况下,如果协议为 http,则端口为 80。所以上面的场景应该会过去。但因为第二个 URI 不包含端口,getPort() returns -1 并将其与 80 进行比较。我如何解释 httphttps 协议的默认端口(80443)?

在测试端口之前,请检查它是否已定义。如果不是,则为其分配默认值。

public static void main(String[] args) throws Exception {

  URI firstURI = new URI("http://example.com:80");
  URI secondURI = new URI("http://example.com/testing");

  boolean sameHost = firstURI.getHost().equals(secondURI.getHost());
  boolean sameScheme = firstURI.getScheme().equals(secondURI.getScheme());
  boolean samePort = getPort(firstURI) == getPort(secondURI);

  if(sameHost && sameScheme && samePort) {
    System.out.println("ok");
  } else {
    System.out.println("error");
  }

}

private static int getPort(URI uri) {
  int port = uri.getPort();
  // if port is undefined, set it to its default value depending on the scheme
  if(port == -1) {
    port = "https".equals(uri.getScheme()) ? 443 : 80;
  }
  return port;
}