Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to concatenate path to base url when a url redirects?

Tags:

java

android

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?

like image 605
user1557330 Avatar asked Jul 27 '12 10:07

user1557330


2 Answers

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/
like image 138
LiuYan 刘研 Avatar answered Oct 28 '22 23:10

LiuYan 刘研


if(!url.contains("index2.html"))
{
   url = url+"index2.html";
}
like image 28
MAC Avatar answered Oct 28 '22 22:10

MAC