【问题标题】:Automatic Cookie Handling C#/.NET HttpWebRequest+HttpWebResponse自动 Cookie 处理 C#/.NET HttpWebRequest+HttpWebResponse
【发布时间】:2010-10-08 23:43:44
【问题描述】:

有什么方法可以在 .NET 中使用 HttpWebRequest/HttpWebResponse 对象自动处理 cookie?我最好只在 .NET 环境中寻找与 LWP::UserAgent 及其行为 (perl) 等效的东西。

有什么建议或意见吗?

【问题讨论】:

    标签: c# .net cookies


    【解决方案1】:

    我认为您正在寻找的是 CookieContainer 类。如果我理解您要正确执行的操作,则您有单独的请求和响应对象,并且您希望将 response cookie 集合转移到下一个 request cookie 集合中自动地。尝试使用此代码:

    CookieContainer cookieJar = new CookieContainer();
    HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://www.google.com");
    request.CookieContainer = cookieJar;
    
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    int cookieCount = cookieJar.Count;
    

    创建cookieJar 并将其设置为请求的CookieContainer 后,它将存储来自响应的所有cookie,因此在上面的示例中,一旦访问Google.com,cookie jar 的计数将为1 .上面请求和响应的 cookie 容器属性将存储一个指向 cookieJar 的指针,因此 cookie 会自动处理并在对象之间共享。

    【讨论】:

      猜你喜欢
      • 2023-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-07
      • 1970-01-01
      • 1970-01-01
      • 2012-12-01
      • 1970-01-01
      相关资源
      最近更新 更多