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();
}