5

我正在请求:

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

根据我发送的论点,我将重定向到这两个之一: http://www.baseaddress.com/path2/
或者 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);
}

你认为这是最好的方法吗?

4

3 回答 3

20

您可以使用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/
于 2012-07-27T10:51:45.160 回答
1
if(!url.contains("index2.html"))
{
   url = url+"index2.html";
}
于 2012-07-27T10:24:27.840 回答
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
于 2012-07-27T11:02:49.740 回答