HTTP 1.1 允許伺服器以 302 狀態碼指示資源暫時移動,新位置在 Location Header。桌面瀏覽器自動追蹤,但移動設備實作差異極大:有的底層協議棧自動處理、有的回傳 302 但 Location 為 null、有的將新 URL 放在回應本文中。
HttpConnection c = (HttpConnection) Connector.open(uri);
int status = c.getResponseCode();
String newUri = c.getHeaderField("Location"); // 可能為 null
if (status == 302) {
c.close();
c = (HttpConnection) Connector.open(newUri); // 這裡會崩潰
}
Location Header。Location 非 null → 關閉舊連線,開新連線至新 URI(標準行為)。Location 為 null → 解析回應本文尋找 "Location" 或 URL 模式。HttpConnection hc = (HttpConnection) Connector.open(uri);
int status = hc.getResponseCode();
String redirect = hc.getHeaderField("Location");
if (status == HttpConnection.HTTP_TEMP_REDIRECT) {
if (redirect != null) {
// 標準行為:重新開啟新連線
hc.close();
hc = (HttpConnection) Connector.open(redirect);
} else {
// 嘗試解析回應本文
redirect = parseContentForLocation(hc); // 自行實作
if (redirect != null) {
hc.close();
hc = (HttpConnection) Connector.open(redirect);
} else {
long start = System.currentTimeMillis();
while (System.currentTimeMillis() - start < 1000) {
Thread.sleep(100);
int newStatus = hc.getResponseCode();
if (newStatus == 200) break; // 底層已完成重定向
}
if (hc.getResponseCode() != 200) {
throw new IOException("Redirect failed");
}
}
}
}
// 繼續處理 200 回應...