Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to follow a "page auto-redirection" to get the response code?

I use the following code to get the returned response code of an aspx page

HttpConnection connection 
     = (HttpConnection) Connector.open("http://company.com/temp1.aspx" 
                                       + ";deviceside=true");
connection.setRequestMethod(HttpConnection.GET);
connection.setRequestProperty(HttpHeaders.HEADER_CONNECTION, "close");
connection.setRequestProperty(HttpHeaders.HEADER_CONTENT_LENGTH, "0");
int resCode = connection.getResponseCode();

It works fine. But what if the link "http://company.com/temp1.aspx" auto-redirects to another page; assume "http://noncompany.com/temp2.aspx" ? How can i get the response code which is returned from the second link (the one which the first link redirected to) ? Is there something like "follow redirection" to get the new response of the page whom was auto-redirected to ?

Thanks in advance.

like image 956
Ashraf Bashir Avatar asked Dec 23 '22 06:12

Ashraf Bashir


1 Answers

I found the solution, Here it is for those who are interested:

int resCode;
String location = "http://company.com/temp1.aspx";
while (true) {  
     HttpConnection connection = (HttpConnection) Connector.open(location + ";deviceside=true");
     connection.setRequestMethod(HttpConnection.GET);
     connection.setRequestProperty(HttpHeaders.HEADER_CONNECTION, "close");
     connection.setRequestProperty(HttpHeaders.HEADER_CONTENT_LENGTH, "0");
     resCode = connection.getResponseCode();
     if( resCode == HttpConnection.HTTP_TEMP_REDIRECT
          || resCode == HttpConnection.HTTP_MOVED_TEMP
          || resCode == HttpConnection.HTTP_MOVED_PERM ) {
          location = connection.getHeaderField("location").trim();
     } else {
          resCode = connection.getResponseCode();
          break;
     }
}
like image 107
Ashraf Bashir Avatar answered Apr 22 '23 08:04

Ashraf Bashir