【问题标题】:how to use cookies with HttpWebRequest如何在 HttpWebRequest 中使用 cookie
【发布时间】:2011-02-27 16:41:27
【问题描述】:

我正在创建一个从网页检索数据的应用程序。该页面受密码保护,并在用户登录时创建 cookie。

为了检索数据,应用程序首先必须登录:使用用户名和密码进行 Web 请求并存储 cookie。然后当 cookie 被存储时,它必须被添加到所有请求的头部中。

这是发出请求并检索内容的方法:

public void getAsyncDailyPDPContextActivationDeactivation()
{
    HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(dailyPDPContextActivationDeactivation);

    IAsyncResult asyncResult = httpWebRequest.BeginGetResponse(null, null);

    asyncResult.AsyncWaitHandle.WaitOne();

    using (HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.EndGetResponse(asyncResult))
    using (StreamReader responseStreamReader = new StreamReader(httpWebResponse.GetResponseStream()))
    {
        string responseText = responseStreamReader.ReadToEnd();
    }
}

有谁知道如何修改此方法以便将 cookie 添加到标头中?

如果有人建议一种方法来存储响应中的 cookie,我也将不胜感激(当应用程序发出请求 http:xxx.xxx.xxx/login?username=xxx&password=xxx 时,cookie 被创建并且必须被存储用于将来的请求)。

【问题讨论】:

    标签: .net httpwebrequest cookies


    【解决方案1】:
    CookieContainer cookieContainer = new CookieContainer();
    HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(...);
    httpWebRequest.CookieContainer = cookieContainer;
    

    然后你在后续请求中重用这个 CookieContainer:

    HttpWebRequest httpWebRequest2 = (HttpWebRequest)WebRequest.Create(...);
    httpWebRequest2.CookieContainer = cookieContainer;
    

    【讨论】:

    • 我实际上不明白。为什么要在即将发送的请求中放入一个新创建的 cookiecontainer(所以它是空的)?稍后您必须用响应填充该 cookieContainer 不应该更合乎逻辑吗?这是有原因的吗?编辑:很多答案都是这样给出的,但我就是不明白为什么会这样。
    • 我的应用程序使用它有不良行为。使用 httpWebRequest2.Headers.Set("Cookie",... 工作正常。
    • 如果我以前登录过该网页,我的 HD 上存储了一个 cookie,因此我可以跳过以编程方式登录。将 cookie 容器分配给 Web 请求会自动搜索并使用找到的 cookie 填充包含,还是您必须手动执行此操作?如果是后者,如何做到这一点?
    • @SteveH。它不会从您的高清中解决。您可以在不同的浏览器上同时运行多个会话,每个会话都有自己的一组相同的 cookie,但值不同。浏览器通常会处理这个问题。
    • @deltu100,如果您在内存中维护对同一对象的引用并将其分配给后续的HttpWebRequest,则会在调用HttpWebRequest.GetResponse() 后填充cookieContainer,它将传递先前检索到的cookies请求。
    【解决方案2】:

    使用CookieContainer 或者您可以使用CookieAwareWebClient

    【讨论】:

      猜你喜欢
      • 2014-04-12
      • 1970-01-01
      • 2019-02-23
      • 1970-01-01
      • 2013-01-11
      • 2011-06-15
      • 2013-03-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多