下面的代碼可以用來處理重定向問題,但是在部分設備中會導致應用程序出錯。
Connection c = (HttpConnection) Connector.open(uri);
int status = c.getResponseCode();
String new_uri = c.getHeaderFIEld("Location"); // new_uri is null on some devices
if (status == 302) {
c.close();
c = (HttpConnection) Connector.open(new_uri); // Breaks here
}
由於重定向是HTTP 1.1的特性,那麼所有1.1兼容的設備都需要考慮這個問題。下面介紹如何解決這個問題。
事實證明在某些設備上,底層的網絡協議棧處理重定向的問題,302響應碼告訴應用程序內部的處理流程。應用程序應該等待直到響應碼等於302。但是有些設備不能正確地從響應中解析出Location字段,這樣Location字段的內容是null,響應碼存儲在了響應的內容之中。有經驗的工程師會采用下面的解決辦法。
1)解析響應,在Location或者響應的內容中查找新地址,如果找到的話關閉以前的連接,轉向新的連接。
2)如果什麼也沒有找到的話,那麼等待10-1000ms,直到狀態碼從302轉變為200。馬上處理響應,當作沒有錯誤發生。
下面的代碼能夠很好的解決重定向的問題,供大家參考和完善。
Connection c = (HttpConnection) Connector.open(uri);
int status = c.getResponseCode();
String redirection = httpConnection.getHeaderFIEld("Location");
if (status == HttpConnection.HTTP_TEMP_REDIRECT) {
if (redirection != null) {
// This the standard HTTP 1.1 behaviour, move on to the redirection uri (basically restarting again).
} else {
// Parse the content of the HTTP response, if any.
// Lookup for a "Location" header, if found, set value to the redirection variable
if (redirection != null) {
// Since location was found, fall back to the standard behaviour.
} else {
long begin_wait = System.currentTimeMillis();
while (System.currentTimeMillis() - begin_wait < 1000 || response != 200) {
sleep(100);
response = httpConnection.getResponseCode();
};
if (response == 200) {
// Once again we're back on tracks, continue processing as if no error has ever happen
} else {
// Here we're really hopeless. Either the server did provided a valid redirection uri,
// or the device did not preserved it. The best option is probably to fail by throwing an exception.
};
};
};
} else // Handle other error codes here
};
// Handle success here (status == 200)