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();
    
  • 相关阅读:
    xpath定向爬取
    正则表达式的零散知识
    正则表达式中的零宽断言
    Cookies
    一行代码从PDF提取Excel文件
    学习kafka的内容总结
    深度学习模型部署
    舆情情感分析
    关键词提取的几种常用方法总结以及代码实现
    语义预训练模型ERNIE
  • 原文地址:https://www.cnblogs.com/cuiweifu/p/3786463.html
Copyright © 2011-2022 走看看