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();
    
  • 相关阅读:
    ios -- 教你如何轻松学习Swift语法(一)
    collectionView,tableView的细节处理
    主流界面搭建原理(类似百思不得姐主界面)
    ios--时间格式化(cell业务逻辑处理)
    test
    Mac下安装Matlab R2015b
    最大奇约数
    编码问题
    最优二叉查找树
    二维数组和二级指针
  • 原文地址:https://www.cnblogs.com/cuiweifu/p/3786463.html
Copyright © 2011-2022 走看看