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?
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/
if(!url.contains("index2.html"))
{
url = url+"index2.html";
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With