How to perform "automatic page redirection" to get a response code?

I am using the following code to get the return response code on 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 great. But what if the link " http://company.com/temp1.aspx " is automatically redirected to another page; suppose http://noncompany.com/temp2.aspx "? How can I get the response code that is returned from the second link (the one from which the first link is redirected)? Is there something like" follow redirection "to get a new response from a page that was automatically redirected to?

Thanks in advance.

+4
source share
2 answers

I found a 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; } } 
+8
source

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

The header of the HTTP header in the response should give you a new host (perhaps it can be used to replace the entire URL).

HttpConnection.HTTP_MOVED_TEMP and HttpConnection.HTTP_MOVED_PERM are two response codes indicating a redirect.

+3
source

All Articles