如何仅更改 java.net.URL 对象的协议部分?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1171513/
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
How to change only the protocol part of a java.net.URL object?
提问by Alceu Costa
I have a java.net.URL object that uses the HTTPS protocol, e.g.:
我有一个使用 HTTPS 协议的 java.net.URL 对象,例如:
https://www.bla.com
And I have to change only the protocol part of this URL object so that when I call it's toString() method I get this:
我只需要更改这个 URL 对象的协议部分,这样当我调用它的 toString() 方法时,我会得到这个:
http://www.bla.com
What is the best way to do that?
最好的方法是什么?
回答by skaffman
You'll have the use the methods available to you:
您将使用可用的方法:
URL oldUrl = new URL("https://www.bla.com");
URL newUrl = new URL("http", oldUrl.getHost(), oldUrl.getPort(), oldUrl.getFile(), oldUrl.getRef());
There's an even more expansive set() method that takes 8 items, you might need that for more elaborate URLs.
还有一个更广泛的 set() 方法,它需要 8 个项目,对于更复杂的 URL,您可能需要它。
Edit: As was just pointed out to me, I wasn't paying attention, and set() is protected. So URL is technically mutable, but to us mortals, it's immutable. So you'll just have to construct a new URL object.
编辑:正如刚刚向我指出的那样,我没有注意,并且 set() 受到保护。所以 URL 在技术上是可变的,但对我们凡人来说,它是不可变的。所以你只需要构造一个新的 URL 对象。
回答by yorick456
You can also use string replacement:
您还可以使用字符串替换:
URL oldUrl = new URL("https://www.bla.com");
String newUrlString = oldUrl.toString().replaceFirst("^https", "http");
URL newUrl = new URL(newUrlString);
回答by nyx
Or you can use org.springframework.web.util.UriComponentsBuilder/ org.springframework.web.util.UriComponents
或者你可以使用org.springframework.web.util.UriComponentsBuilder/org.springframework.web.util.UriComponents

