• too many automatic redirections were attempted


    用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();
    
  • 相关阅读:
    设置装订线
    设置页边距
    查看压缩文件的信息
    格式化3
    格式化2
    条件格式化1
    单独设置奇偶页的页眉页脚
    方法重写注意点
    super注意点
    稀疏数组的压缩和还原
  • 原文地址:https://www.cnblogs.com/cuiweifu/p/3786463.html
Copyright © 2020-2023  润新知