开发者

Modifying the port of a URI

In Java, the URI class is immutable.

Here's how I'm currently modifying the port:

public URI uriWithPort(URI uri, int p开发者_JAVA技巧ort) {
    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?


You can also use URIBuider

http://download.oracle.com/javaee/6/api/javax/ws/rs/core/UriBuilder.html

UriBuilder.fromURI(uri).port(port).build("foo", "bar");


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)...


Creating a new URL object from an existing one seems like a simple thing to do:

URL originalURL = new URL("http://octopus:345/squid.html");
URL newURL = new URL(originalURL.getProtocol(), originalUrl.getHost(), newPort, originalURL.getFile());


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"));
    }


What about using uri.resolve(URI)? Or use URI.create(URI)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜