问题描述
在网上找了一个C#发请的请求中使用Cookie,其中privatestaticstringSendHttpRequestGet(stringurl,Encodingencoding,CookieContainercookieContainer){if(string.IsNullOrEmpty(url))thrownewArgumentNullException("url");if(encoding==null)thrownewArgumentNullException("encoding");HttpWebRequestrequest=(HttpWebRequest)WebRequest.Create(url);request.Method="GET";request.CookieContainer=cookieContainer;using(WebResponseresponse=request.GetResponse()){using(StreamReaderreader=newStreamReader(response.GetResponseStream(),encoding)){returnreader.ReadToEnd();}}}privatevoidSendHttpDEMO(){StringBuildersb=newStringBuilder();CookieContainercookieContainer=newCookieContainer();stringurl="http://www.taobao.com";SendHttpRequestGet(url,Encoding.Default,cookieContainer);//后面可以继续发起HTTP请求,此时将会包含上次从服务器写入的Cookie//SendHttpRequestGet("同域名下的其它URL",Encoding.Default,cookieContainer);//至此,我们可以显示取得了哪些CookieCookieCollectioncookies=cookieContainer.GetCookies(newUri(url));if(cookies!=null){foreach(System.Net.Cookiecookieincookies)sb.AppendLine(cookie.ToString());}txtCookies.Text=sb.ToString();}当后面继续发送请求时,并没有包含上次从服务器写入的cookie。