.net 如何在 HttpWebRequest 中使用 cookie
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2972643/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to use cookies with HttpWebRequest
提问by Niko Gamulin
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.
我正在创建一个用于从网页检索数据的应用程序。该页面受密码保护,并在用户登录时创建 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.
为了检索数据,应用程序首先必须登录:使用用户名和密码发出 Web 请求并存储 cookie。然后在存储 cookie 时,必须将其添加到所有请求的标头中。
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();
}
}
Does anyone know how to modify this method in order to add a cookie into the header?
有谁知道如何修改此方法以将 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).
如果有人建议从响应中存储 cookie 的方法,我也会很感激(当应用程序发出请求 http:xxx.xxx.xxx/login?username=xxx&password=xxx cookie 被创建并且必须存储以备将来请求)。
回答by k_b
CookieContainer cookieContainer = new CookieContainer();
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(...);
httpWebRequest.CookieContainer = cookieContainer;
Then you reuse this CookieContainer in subsequent requests:
然后在后续请求中重用这个 CookieContainer:
HttpWebRequest httpWebRequest2 = (HttpWebRequest)WebRequest.Create(...);
httpWebRequest2.CookieContainer = cookieContainer;
回答by Don
Use the CookieContaineror you could use a CookieAwareWebClient
使用CookieContainer或者你可以使用CookieAwareWebClient

