如何在 HttpWebRequest 中使用 cookie [英] how to use cookies with HttpWebRequest

查看:87
本文介绍了如何在 HttpWebRequest 中使用 cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am creating an application for data retrieval from the web page. The page is password protected and when the user logs in the cookie is created.

为了检索数据,应用程序首先必须登录:使用用户名和密码发出 Web 请求并存储 cookie.然后在存储 cookie 时,必须将其添加到所有请求的标头中.

In order to retrieve the data the application first has to log in: make web request with username and password and store the cookie. Then when the cookie is stored it has to be added into the headers of all requests.

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

Here is the method which makes requests and retrieves the content:

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添加到标题中?

Does anyone know how to modify this method in order to add a cookie into the header?

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

I would be also thankful if anyone suggested a way to store cookie from the response (when the application makes a request http:xxx.xxx.xxx/login?username=xxx&password=xxx the cookie is created and has to be stored for future requests).

推荐答案

CookieContainer cookieContainer = new CookieContainer();
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(...);
httpWebRequest.CookieContainer = cookieContainer;

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

Then you reuse this CookieContainer in subsequent requests:

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

这篇关于如何在 HttpWebRequest 中使用 cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆