簡體   English   中英

如何僅更改 java.net.URL object 的協議部分?

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

我有一個使用 HTTPS 協議的 java.net.URL object,例如:

https://www.bla.com

我只需要更改這個 URL object 的協議部分,這樣當我調用它的 toString() 方法時,我得到這個:

http://www.bla.com

最好的方法是什么?

您將使用可用的方法:

URL oldUrl = new URL("https://www.bla.com");
URL newUrl = new URL("http", oldUrl.getHost(), oldUrl.getPort(), oldUrl.getFile(), oldUrl.getRef());

有一個更廣泛的set()方法需要8個項目,您可能需要更精細的URL。

編輯:正如剛剛向我指出的那樣,我沒有注意,並且set()受到保護。 所以URL在技術上是可變的,但對於我們凡人來說,它是不可改變的。 所以你只需構建一個新的URL對象。

您還可以使用字符串替換:

URL oldUrl = new URL("https://www.bla.com");
String newUrlString = oldUrl.toString().replaceFirst("^https", "http");
URL newUrl = new URL(newUrlString);

或者你可以使用org.springframework.web.util.UriComponentsBuilder / org.springframework.web.util.UriComponents

請參閱: Java中是否存在可變的URL / URI對象?

看來他們忘了讓他們的 class 有用。 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());
    }
}

建議使用字符串替換的答案更短,但如果您想更改任何其他 URL 組件,您將需要這樣的東西。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM