java 修改 URI 的端口
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6490014/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Modifying the port of a URI
提问by Marty Pitt
In Java, the URI
class is immutable.
在 Java 中,URI
类是不可变的。
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?
有没有更简单的方法?
采纳答案by T.J. Crowder
No, that's pretty much it. 'Tis a bit verbose, granted, but it's not thatcomplicated. :-)
不,差不多就是这样。'这有点冗长,当然,但它并没有那么复杂。:-)
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)...
如果您使用的是 Java EE 而不仅仅是 JDK,请参阅Talha Ahmed Khan 的回答,其中使用了 Java EE 的UriBuilder
,它仍然是单行但更优雅。那不是 JDK 的一部分,但是如果您正在执行 servlet 或类似的操作(或者不介意包含必要的 jar)...
回答by Talha Ahmed Khan
You can also use URIBuider
你也可以使用 URIBuider
http://download.oracle.com/javaee/6/api/javax/ws/rs/core/UriBuilder.html
http://download.oracle.com/javaee/6/api/javax/ws/rs/core/UriBuilder.html
UriBuilder.fromURI(uri).port(port).build("foo", "bar");
回答by Dariush Jafari
Creating a new URL object from an existing one seems like a simple thing to do:
从现有的 URL 对象创建一个新的 URL 对象似乎是一件简单的事情:
URL originalURL = new URL("http://octopus:345/squid.html");
URL newURL = newURL(originalURL.getProtocol(), originalUrl.getHost(), newPort, originalURL.getFile());
回答by spot35
What about using uri.resolve(URI)
? Or use URI.create(URI)
怎么用uri.resolve(URI)
?或使用URI.create(URI)