Nik*_*lin 25 .net cookies httpwebrequest
我正在从网页创建一个数据检索应用程序.该页面受密码保护,并在用户登录时创建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();
}
}
Run Code Online (Sandbox Code Playgroud)
有谁知道如何修改此方法,以便将cookie添加到标题中?
如果有人建议从响应中存储cookie的方式(当应用程序发出请求http:xxx.xxx.xxx/login?username = xxx&password = xxx时,cookie已创建并且必须存储以备将来请求)我也会感激不尽).
k_b*_*k_b 36
CookieContainer cookieContainer = new CookieContainer();
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(...);
httpWebRequest.CookieContainer = cookieContainer;
Run Code Online (Sandbox Code Playgroud)
然后在后续请求中重用此CookieContainer:
HttpWebRequest httpWebRequest2 = (HttpWebRequest)WebRequest.Create(...);
httpWebRequest2.CookieContainer = cookieContainer;
Run Code Online (Sandbox Code Playgroud)