代码改变世界

too many automatic redirections were attempted

2014-01-16 22:05 Franz 阅读(...) 评论(...) 编辑 收藏

用HttpClient时发现一下页面跳转现象.

页面A要求授权自动跳转到页面B, 页面B进行了授权,在HTTP Header里要求SetCookie并跳转到页面A. 再次请求页面A的时候没有带上此Cookie信息, 页面A的服务器发现没有授权, 就去页面B进行授权. 导致了一个死循环.

最终会抛出一个”too many automatic redirections were attempted”的异常信息.

这个问题可参看http://stackoverflow.com/questions/518181/too-many-automatic-redirections-were-attempted-error-message-when-using-a-http 文章描述.

如果在.NET4.5上可以这么搞:

var baseAddress = new Uri("http://example.com");
var cookieContainer = new CookieContainer();
using (var handler = new HttpClientHandler() { CookieContainer = cookieContainer })
using (var client = new HttpClient(handler) { BaseAddress = baseAddress })
{
    var content = new FormUrlEncodedContent(new[]
    {
        new KeyValuePair<string, string>("foo", "bar"),
        new KeyValuePair<string, string>("baz", "bazinga"),
    });
    cookieContainer.Add(baseAddress, new Cookie("CookieName", "cookie_value"));
    var result = client.PostAsync("/test", content).Result;
    result.EnsureSuccessStatusCode();
}

但是如果低于4.5的版本, 就只能自己在HttpWebRequest对象上的搞了, 就像这样

Uri site = new Uri("http://www.google.com");
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(site);
CookieContainer cookies = new CookieContainer();
request.CookieContainer = cookies;

//Print out the number of cookies before the response (of course it will be blank)
Console.WriteLine(cookies.GetCookieHeader(site));

//Get the response and print out the cookies again
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
    Console.WriteLine(cookies.GetCookieHeader(site));
}

Console.ReadKey();