Reputation: 129
I'm making a request to:
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
The problem is that the respond returns only:
index2.html
or /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?
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?
Upvotes: 5
Views: 22631
Reputation: 171
You can use the Java class URI
function resolve
to merge these URIs.
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
Upvotes: 1
Reputation: 1624
You can use java.net.URI.resolve to determine the redirected absolute 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/
Upvotes: 22