2012-07-27 58 views
0

我正在做一个请求:如何在URL重定向时连接到基础url的路径?

http://www.baseaddress.com/path/index1.html

据我送,我得到一个重定向到这两者之一的参数: http://www.baseaddress.com/path2/
OR http://www.baseaddress.com/path/index2.html

的问题是仅回复回复: index2.html/path2/

现在我检查第一个字符是否为/,并根据此连接URL。 有没有一个简单的方法来做到这一点没有字符串检查?

代码:

url = new URL("http://www.baseaddress.com/path/index1.php"); 
con = (HttpURLConnection) url.openConnection(); 
... some settings 
in = con.getInputStream(); 
redLoc = con.getHeaderField("Location"); // returns "index2.html" or "/path2/" 
if(redLoc.startsWith("/")){ 
    url = new URL("http://www.baseaddress.com" + redLoc); 
}else{ 
    url = new URL("http://www.baseaddress.com/path/" + redLoc); 
} 

你觉得这是最好的方法是什么?

+2

请你能展现最佳的答案代码。 – 2012-07-27 10:18:44

回答

7

您可以使用java.net.URI.resolve来确定重定向的绝对URL。

java.net.URI uri = new java.net.URI ("http://www.baseaddress.com/path/index1.html"); 
System.out.println (uri.resolve ("index2.html")); 
System.out.println (uri.resolve ("/path2/")); 

输出

http://www.baseaddress.com/path/index2.html 
http://www.baseaddress.com/path2/ 
1
if(!url.contains("index2.html")) 
{ 
    url = url+"index2.html"; 
} 
1

您可以使用Java类URI功能resolve合并这些URI。

public String mergePaths(String oldPath, String newPath) { 
    try { 
     URI oldUri = new URI(oldPath); 
     URI resolved = oldUri.resolve(newPath); 
     return resolved.toString(); 
    } catch (URISyntaxException e) { 
     return oldPath; 
    } 
} 

例子:

System.out.println(mergePaths("http://www.baseaddress.com/path/index.html", "/path2/")); 
System.out.println(mergePaths("http://www.baseaddress.com/path/index.html", "index2.html")); 

将输出:

http://www.baseaddress.com/path2/ 
http://www.baseaddress.com/path/index2.html