/** * Return a URI with a defined port number, if possible. If the URI * has no port number then the argument-supplied (schema,port) mapping is * used if the scheme matches, otherwise default port numbers are used if a * default port is known for this scheme. */ public static URI withDefaultPort(URI uri, String scheme, int port) { if (isDefaultPortNeeded(uri)) { int defaultPort = portWithDefault(uri, scheme, port); if (defaultPort != -1) { try { return new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), defaultPort, uri.getPath(), uri.getQuery(), uri.getFragment()); } catch (URISyntaxException e) { throw new RuntimeException("Failed to add default port: " + e.getMessage(), e); } } } return uri; }