日期:2014-05-20 浏览次数:20792 次
下面的代码可以用来处理重定向问题,但是在部分设备中会导致应用程序出错。 Connection c = (HttpConnection) Connector.open(uri); ? int status = c.getResponseCode();? 事实证明在某些设备上,底层的网络协议栈处理重定向的问题,302响应码告诉应用程序内部的处理流程。应用程序应该等待直到响应码等于302。但是有些设备不能正确地从响应中解析出Location字段,这样Location字段的内容是null,响应码存储在了响应的内容之中。有经验的工程师会采用下面的解决办法。 1)解析响应,在Location或者响应的内容中查找新地址,如果找到的话关闭以前的连接,转向新的连接。 2)如果什么也没有找到的话,那么等待10-1000ms,直到状态码从302转变为200。马上处理响应,当作没有错误发生。 下面的代码能够很好的解决重定向的问题,供大家参考和完善。 Connection c = (HttpConnection) Connector.open(uri);? // Handle success here (status == 200) 您还可以了解一下Http协议的细节,http://www.ietf.org/rfc/rfc2616.txt。原文地址
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兼容的设备都需要考虑这个问题。下面介绍如何解决这个问题。
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
};