/*代码如下,获得Cookie,再发送过去*/
/*获取网站的Cook,cook储存在response.Cookies*/
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost:52273/Default.aspx");
request.CookieContainer = new CookieContainer();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
/*访问该网站,把获得的Cook再传过去*/
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://localhost:52273/Default.aspx");
CookieContainer container = new CookieContainer();
for(int i=0;i<response.Cookies.Count;i++)
container.Add(response.Cookies[i]);
req.CookieContainer = container;
HttpWebResponse res = (HttpWebResponse)req.GetResponse();
//读取网站里的所有数据
Stream stream = res.GetResponseStream();
StreamReader streamReader = new StreamReader(stream);
String str = streamReader.ReadToEnd();
MessageBox.Show(str);
以下是MSDN里获得网页Cookie的方法
usingSystem.Net;
usingSystem;
namespaceExamples.System.Net.Cookies
{
// This example is run at the command line.
// Specify one argument: the name of the host to
// send the request to.
// If the request is sucessful, the example displays the contents of the cookies
// returned by the host.
publicclassCookieExample
{
publicstaticvoidMain(string[] args)
{
if(args == null|| args.Length != 1)
{
Console.WriteLine("Specify the URL to receive the request.");
Environment.Exit(1);
}
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(args[0]);
request.CookieContainer = newCookieContainer();
HttpWebResponse response = (HttpWebResponse) request.GetResponse();
// Print the properties of each cookie.
foreach(Cookie cook inresponse.Cookies)
{
Console.WriteLine("Cookie:");
Console.WriteLine("{0} = {1}", cook.Name, cook.Value);
Console.WriteLine("Domain: {0}", cook.Domain);
Console.WriteLine("Path: {0}", cook.Path);
Console.WriteLine("Port: {0}", cook.Port);
Console.WriteLine("Secure: {0}", cook.Secure);
Console.WriteLine("When issued: {0}", cook.TimeStamp);
Console.WriteLine("Expires: {0} (expired? {1})",
cook.Expires, cook.Expired);
Console.WriteLine("Don't save: {0}", cook.Discard);
Console.WriteLine("Comment: {0}", cook.Comment);
Console.WriteLine("Uri for comments: {0}", cook.CommentUri);
Console.WriteLine("Version: RFC {0}", cook.Version == 1 ? "2109": "2965");
// Show the string representation of the cookie.
Console.WriteLine ("String: {0}", cook.ToString());
}
}
}
}
/*手动添加Cookie,然后发送给服务页面*/
/*设置Cookie*/
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost:52273/Default.aspx");
CookieContainer container = new CookieContainer();
Cookie cook =new Cookie("ucel","verygood!");
cook.Domain="localhost";
container.Add(cook);
request.CookieContainer = container;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
//读取网站里的所有数据
Stream stream = response.GetResponseStream();
StreamReader streamReader = new StreamReader(stream);
String str = streamReader.ReadToEnd();
MessageBox.Show(str);
Environment.Exit(0);
上面Cookie里的Domain填的是网站服务器的主机名,可填IP地址。