Modifying the port of a URI

Viewed 18760

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?

5 Answers

here is an another solution that handles common and not well formatted urls. You can enhance it to be more sophisticated.

    private static final Pattern URL_PATTERN =
        Pattern.compile("^((?<protocol>.*)(?::\\/\\/))?(?<host>.*?)((?::)(?<port>\\d+))?(?:\\/)(?<path>.*)");
    ...

    public static String replacePortInURL(String urlString, String newPort) {
        if (urlString == null) {
            return null;
        }
        if (StringUtils.isBlank(urlString)) {
            return newPort;
        }
        Matcher matcher = URL_PATTERN.matcher(urlString);
        if (!matcher.find()) {
            return urlString;
        }
        Map<String, String> urlParts = Arrays.stream(new String[] { "protocol", "host", "port", "path" })
            .collect(HashMap::new, (map, partName) -> map.put(partName, matcher.group(partName)), HashMap::putAll);
        urlParts.put("port", newPort);
        return urlParts.get("protocol") == null
            ? String.format("%s:%s/%s", urlParts.get("host"), urlParts.get("port"), urlParts.get("path"))
            : String.format("%s://%s:%s/%s", urlParts.get("protocol"), urlParts.get("host"), urlParts.get("port"), urlParts.get("path"));
    }
Related