http 301、302 重定向,處理過程分析

http 301、302 重定向,處理過程分析

一、定義:
    響應碼:301、302 ,都代表重定向,其中 301 代表永久重定向,302 代表臨時重定向;

二、服務器場景:
    請求 www.aa.com/a.html ,重定向到 www.aa.com/b.html;
    請求 www.aa.com/b.html ,重定向到 www.aa.com/c.html;

三、客戶端場景:
    請求 www.aa.com/a.html,瀏覽器展現了 www.aa.com/c.html 內容;其中隱藏了 b.html 到 c.html 過程。


四、重定向時客戶端發生了什麼?
使用 firefox 調試工具可以看到如下過程:
    www.aa.com/a.html    302
    www.aa.com/b.html    302
    www.aa.com/c.html    200

瀏覽器發現響應碼爲 301、302 時,將讀取 header 中的 location 值,重新發起請求;
    www.aa.com/a.html    302
        headers.location = www.aa.com/b.html
    www.aa.com/b.html    302
        headers.location = www.aa.com/c.html
    www.aa.com/c.html    200


五、c# 模擬重定向處理過程,跟蹤重定向過程

public static string RedirectPath(string url)
{
    StringBuilder sb = new StringBuilder();
    string location = string.Copy(url);
    while (!string.IsNullOrWhiteSpace(location))
    {
        sb.AppendLine(location); // you can also use 'Append'
        HttpWebRequest request = HttpWebRequest.CreateHttp(location);
        request.AllowAutoRedirect = false;
        using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
        {
            //讀取 header 中的 locantion 值
            location = response.GetResponseHeader("Location");
        }
    }
    return sb.ToString();
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章