我使用以下代碼合併兩個URL。在JAVA中合併兩個URL
String strUrl1 = "http://www.domainname.com/path1/2012/04/25/file.php";
String arg = "?page=2";
URL url1;
try {
url1 = new URL(strUrl1);
URL reconUrl1 = new URL(url1,arg);
System.out.println(" url : " + reconUrl1.toString());
} catch (MalformedURLException ex) {
ex.printStackTrace();
}
我對結果大吃一驚:http://www.domainname.com/path1/2012/04/25/?page=2
我希望它是(什麼瀏覽器做):http://www.domainname.com/path1/2012/04/25/file.php?page=2
臨屋的javadoc關於構造URL(網址背景下,字符串規範)解釋它應該尊重RFC。
我做錯了什麼?
感謝
UPDATE:
This is the only problem I encountered with the fonction.
The code already works in all others cases, like browser do
"domain.com/folder/sub" + "/test" -> "domain.com/test"
"domain.com/folder/sub/" + "test" -> "domain.com/folder/sub/test"
"domain.com/folder/sub/" + "../test" -> "domain.com/folder/test"
...
它更復雜,因爲代碼應該能夠處理所有其他情況下,已經爲我添加URL所梅索德處理我的問題 – benfromaix 2012-04-27 14:15:12
在這種情況下,我認爲@Anurag Ramdasan/aioobe答案更適合你。基本上URLContext將刪除「file.php」。但只要你能夠減去這個值並將其用作URL參數,你就可以走了。 – Rudy 2012-04-30 07:20:22