zoukankan      html  css  js  c++  java
  • 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();
    
  • 相关阅读:
    C#生成图形验证码
    飞刀软件官网正式开通
    IIS7或者IIS7.5部署MVC项目时出现404错误
    office编程必不可少 [转]
    C# 利用 HttpWebRequest 和 HttpWebResponse 模拟登录有验证码的网站
    console方便用法
    24个解决实际问题的ES6代码段
    遍历对象的属性和对象的值
    前端图片处理
    Vue团队代码规范
  • 原文地址:https://www.cnblogs.com/cuiweifu/p/3786463.html
Copyright © 2011-2022 走看看