[英]How to build an absolute URL from a relative URL using Java?
我有一個相對的url字符串,知道主機和協議。 如何建立絕對網址字串?
看起來容易嗎? 乍一看是肯定的,但是直到轉義字符出現。 我必須從302代碼http(s)響應Location標頭構建絕對URL。
讓我們考慮一個例子
protocol: http
host: example.com
location: /path/path?param1=param1Data¶m2= "
首先,我嘗試構建如下的url字符串:
Sting urlString = protocol+host+location
URL類的構造函數不能轉義空格和雙引號:
new URL(urlString)
URI類的構造函數失敗,並發生以下異常:
new URI(urlString)
URI.resolve
方法也因異常而失敗
然后,我發現URI可以轉義查詢字符串中的參數,但是只有少數構造函數,例如:
URI uri = new URI("http", "example.com",
"/path/path", "param1=param1Data¶m2= \"", null);
此構造函數需要將path和query作為單獨的參數,但是我有一個相對URL ,並且不會按path和query部分拆分。
我可以考慮檢查相對網址是否包含“?” 問號,並想想它之前的所有內容都是路徑,而它之后的所有內容都是查詢,但是如果相對網址不包含路徑,而僅包含查詢,並且查詢包含“?”,該怎么辦? 標志? 然后這將不起作用,因為查詢的一部分將被視為路徑。
現在,我無法獲得如何從相對URL構建絕對URL。
這些公認的答案似乎是錯誤的:
最好考慮以下情形:相對於主機和某些路徑部分的URL給出相對URL:
初始網址http://example.com / ...一些路徑...相對/ home?...在此處查詢...
盡管仍然可以使用良好的庫,但獲得Java核心解決方案將是很棒的。
第一個?
指示查詢字符串的開始位置:
[...]查詢組件由第一個問號(
?
)字符指示,並由數字符號(#
)字符或URI末尾終止。
一種簡單的方法(不會處理片段,並假定查詢字符串始終存在)很簡單:
String protocol = "http";
String host = "example.com";
String location = "/path/path?key1=value1&key2=value2";
String path = location.substring(0, location.indexOf("?"));
String query = location.substring(location.indexOf("?") + 1);
URI uri = new URI(protocol, host, path, query, null);
也可以處理碎片的更好方法是:
String protocol = "http";
String host = "example.com";
String location = "/path/path?key1=value1&key2=value2#fragment";
// Split the location without removing the delimiters
String[] parts = location.split("(?=\\?)|(?=#)");
String path = null;
String query = null;
String fragment = null;
// Iterate over the parts to find path, query and fragment
for (String part : parts) {
// The query string starts with ?
if (part.startsWith("?")) {
query = part.substring(1);
continue;
}
// The fragment starts with #
if (part.startsWith("#")) {
fragment = part.substring(1);
continue;
}
// Path is what's left
path = part;
}
URI uri = new URI(protocol, host, path, query, fragment);
最好的方法似乎是使用多段構造函數創建URI對象,然后將其轉換為如下所示的URL:
URI uri = new URI("https", "sitename.domain.tld", "/path/goes/here", "param1=value¶m2=otherValue");
URL url = uri.toURL();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.