我使用以下代码合并两个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