Ashraf Bashir
Ashraf Bashir

Reputation: 9804

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.

Upvotes: 4

Views: 1598

Answers (2)

Ashraf Bashir
Ashraf Bashir

Reputation: 9804

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;
     }
}

Upvotes: 8

michael aubert
michael aubert

Reputation: 6826

You need to code your HttpConnection inside a loop that follows HTTP redirections based on the response code.

The HTTP header "location" in the response is supposed to give you a new host (maybe it can be used to replace the entire URL).

HttpConnection.HTTP_MOVED_TEMP and HttpConnection.HTTP_MOVED_PERM are the two response code that indicate a redirection.

Upvotes: 3

Related Questions