java url重定向时如何将路径连接到基本url?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11685801/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to concatenate path to base url when a url redirects?
提问by user1557330
I'm making a request to:
我提出以下要求:
http://www.baseaddress.com/path/index1.html
http://www.baseaddress.com/path/index1.html
According to the arguments I sent, I'm getting a redirect to one of this two:
http://www.baseaddress.com/path2/
OR
http://www.baseaddress.com/path/index2.html
根据我发送的参数,我将重定向到以下两者之一:
http://www.baseaddress.com/path2/
或
http://www.baseaddress.com/path/index2.html
The problem is that the respond returns only:
index2.html
or /path2/
问题是响应仅返回:
index2.html
或/path2/
for now I check if the first char is /
, and concatenate the URL according to this.
Is there a simple method for doing this without string checking?
现在我检查第一个字符是否为/
,并根据此连接 URL。有没有一种简单的方法可以在没有字符串检查的情况下做到这一点?
the code:
代码:
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);
}
do you think this is the best method?
你认为这是最好的方法吗?
回答by u404192
You can use java.net.URI.resolveto determine the redirected absolute URL.
您可以使用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/"));
Output
输出
http://www.baseaddress.com/path/index2.html
http://www.baseaddress.com/path2/
回答by MAC
if(!url.contains("index2.html"))
{
url = url+"index2.html";
}
回答by alaeus
You can use the Java class URI
function resolve
to merge these URIs.
您可以使用 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;
}
}
Example:
例子:
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"));
Will output:
将输出:
http://www.baseaddress.com/path2/
http://www.baseaddress.com/path/index2.html