国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 編程應用 > 正文

Java ME應用設計指南之聯網重定向

2019-11-18 16:17:20
字體:
來源:轉載
供稿:網友

HTTP 1.1協議允許Web服務器臨時改變資源的位置,也就是說你訪問的資源在另外一個地址。這時候服務器返回的響應代碼是302,而新的地址存放在Header中,Header的名稱是Location。正常情況下,客戶端瀏覽器應該指向臨時的訪問地址。但是,移動終端設備差距很大,在處理302返回碼的時候,設備之間的行為差異很大。

下面的代碼可以用來處理重定向問題,但是在部分設備中會導致應用程序出錯。

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)


您還可以了解一下Http協議的細節,http://www.ietf.org/rfc/rfc2616.txt。本文是筆者在閱讀SUN的技術文章的時候編譯的。您可以通過下面的地址閱讀原文,也歡迎您編譯其他的好文章,共同促進國內java ME技術的發展。

(出處:http://m.survivalescaperooms.com)



發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 通辽市| 开化县| 荥阳市| 汾阳市| 左贡县| 西昌市| 平和县| 南充市| 乐昌市| 南溪县| 甘孜县| 东乡族自治县| 长泰县| 徐水县| 大理市| 洛宁县| 马鞍山市| 霞浦县| 花莲县| 襄城县| 沙田区| 钦州市| 阿荣旗| 兴城市| 余江县| 沙洋县| 桃江县| 尉氏县| 海门市| 翁牛特旗| 黑山县| 永靖县| 北碚区| 饶河县| 五大连池市| 瓦房店市| 扬中市| 望都县| 达日县| 丁青县| 新宁县|