日期:2014-05-17  浏览次数:21079 次

200分求教:webRequest 如何获取和保持cookies!
需求:想在内部系统加入google检索,用webrequest获取结果,然后按我自己的格式显示结果。我想让google按照http://www.google.cn/preferences?hl=zh-CN中设置,返回结果。

最好能用WebRequest获取cookies然后,每次检索都带上cookies,最好不用webbrowse.

请高手帮助!

------解决方案--------------------
http://www.cnblogs.com/goody9807/archive/2008/06/26/1107560.html
------解决方案--------------------
WebRequest是获取一个url即外界的信息的,cookie是你本机上的东西,检索的时候带上cookie是什么意思呢 ?
------解决方案--------------------
程序想网页传递参数用post
探讨
http://www.cnblogs.com/goody9807/archive/2008/06/26/1107560.html

------解决方案--------------------
public static void Main(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 = new CookieContainer();

HttpWebResponse response = (HttpWebResponse) request.GetResponse();



// Print the properties of each cookie.
foreach (Cookie cook in response.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());
}
}

------解决方案--------------------
探讨
程序想网页传递参数用post
引用:
http://www.cnblogs.com/goody9807/archive/2008/06/26/1107560.html


------解决方案--------------------
设置CookieContainer属性就可以,这个值默认是null,当它为null代表不接受cookie。


------解决方案--------------------
注意WebRequest不支持cookie的,但是HttpWebRequest,你可以显式地置换一下。
------解决方案--------------------
C# code


HttpWebRequest w = (HttpWebRequest)WebRequest.Create("http://www.google.cn");
CookieContainer cookie = new CookieContainer();
w.CookieContainer = cookie;
//...

------解决方案--------------------
C# code
        public string Login(string url, string usr, string pass)
        {
            string Return = null;

            this.LoginUrl = url;

            string loginstr = "rl=%2Fhome%2F&email=" + usr + "&password=" + pass;

            loginstr = EncodePost(loginstr);
            byte[] replybyte = Encoding.UTF8.GetBytes(loginstr);

            try
            {
                CookieC