我正在请求:
http://www.baseaddress.com/path/index1.html
根据我发送的论据,我正在重定向到这两个中的一个:
http://www.baseaddress.com/path2/
要么
http://www.baseaddress.com/path/index2.html
问题是响应仅返回:
index2.html
或/path2/
现在我检查第一个char是否为/
,并根据此连接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);
}
你认为这是最好的方法吗?
答案 0 :(得分:14)
您可以使用java.net.URI.resolve来确定重定向的绝对网址。
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 :(得分:1)
if(!url.contains("index2.html"))
{
url = url+"index2.html";
}
答案 2 :(得分: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