简体   繁体   English

如何仅更改 java.net.URL object 的协议部分?

[英]How to change only the protocol part of a java.net.URL object?

I have a java.net.URL object that uses the HTTPS protocol, eg:我有一个使用 HTTPS 协议的 java.net.URL object,例如:

https://www.bla.com

And I have to change only the protocol part of this URL object so that when I call its toString() method I get this:我只需要更改这个 URL object 的协议部分,这样当我调用它的 toString() 方法时,我得到这个:

http://www.bla.com

What is the best way to do that?最好的方法是什么?

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. 编辑:正如刚刚向我指出的那样,我没有注意,并且set()受到保护。 So URL is technically mutable, but to us mortals, it's immutable. 所以URL在技术上是可变的,但对于我们凡人来说,它是不可改变的。 So you'll just have to construct a new URL object. 所以你只需构建一个新的URL对象。

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

Or you can use org.springframework.web.util.UriComponentsBuilder / org.springframework.web.util.UriComponents 或者你可以使用org.springframework.web.util.UriComponentsBuilder / org.springframework.web.util.UriComponents

see: Does there exist a mutable URL/URI object in Java? 请参阅: Java中是否存在可变的URL / URI对象?

It appears they forgot to make their class useful.看来他们忘了让他们的 class 有用。 Stealing code from URL.toExternalForm() helps:URL.toExternalForm()窃取代码有助于:

public class ICantBelieveThisIsNotInTheStandardLibrary {
    public static final URL makeCopyWithDifferentProtocol(URL u, String protocol) {
        StringBuffer result = new StringBuffer();
        result.append(protocol);
        result.append(":");
        if (u.getAuthority() != null && u.getAuthority().length() > 0) {
            result.append("//");
            result.append(u.getAuthority());
        }
        if (u.getPath() != null) {
            result.append(u.getPath());
        }
        if (u.getQuery() != null) {
            result.append('?');
            result.append(u.getQuery());
        }
        if (u.getRef() != null) {
            result.append("#");
            result.append(u.getRef());
        }
        return new URL(result.toString());
    }
}

The answer which suggests to use a String-replacement is shorter, but you are going to need something like this if you ever want to change any of the other URL components.建议使用字符串替换的答案更短,但如果您想更改任何其他 URL 组件,您将需要这样的东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM