In Java, the URI class is immutable.
Here’s how I’m currently modifying the port:
public URI uriWithPort(URI uri, int port) {
try {
return new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), port,
uri.getPath(), uri.getQuery(), uri.getFragment());
} catch (URISyntaxException e) {
LOG.error("Updating URI port failed:",e);
return uri;
}
}
Is there a simpler way?
No, that’s pretty much it. ‘Tis a bit verbose, granted, but it’s not that complicated. 🙂
If you’re using Java EE rather than just the JDK, see Talha Ahmed Khan’s answer, which uses Java EE’s
UriBuilder, which is still a one-liner but more elegant. That’s not part of the JDK, but if you’re doing a servlet or similar (or don’t mind including the necessary jar)…