我们都有过模拟登录一些网站,然后抓取数据的经验,但是这次不同,这次是想从我的网站真正登录到另外一个网站,例如从我这,点一个按钮,就可以自动登录到csdn。
这我就有点不知道怎么做了,平时都是获取到repsonse然后分析就哦了,这次有点蒙。但我现在的想法是,先模拟登录请求,获取repsonse回来的cookie,然后写入默认浏览器,之后直接redrict过去。可是一直不行啊一直找不到返回的cookie。我是用的如下方法。
public static string GetResponse(string url, string method, string data,string refer)
        {
            try
            {
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
                req.Headers.Add("x-requested-with", "XMLHttpRequest");
                req.Headers.Set("Cache-Control", "no-cache");
                req.Headers.Set("Accept-Encoding", "gzip, deflate");
                req.Headers.Set("Accept-Language", "zh-cn");                req.Accept = "image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/xaml+xml, application/x-ms-xbap, application/x-ms-application, application/vnd.ms-xpsdocument, */*";
                req.Referer = refer;                req.KeepAlive = true;
                req.Method = method.ToUpper();
                req.AllowAutoRedirect = true;
                req.CookieContainer = CookieContainers;
                req.ContentType = "application/x-www-form-urlencoded";
                req.UserAgent = IE9;
                req.Timeout = 50000;
                if (method.ToUpper() == "POST" && data != null)
                {
                    ASCIIEncoding encoding = new ASCIIEncoding();
                    byte[] postBytes = encoding.GetBytes(data);
                    //如果为0也要写,不然会报错:远程服务器返回错误: (411) 所需的长度。
                    req.ContentLength = postBytes.Length;
                    if (data != "")
                    {
                        Stream st = req.GetRequestStream();
                        st.Write(postBytes, 0, postBytes.Length);
                        st.Close();
                    }
                }                HttpWebResponse res = (HttpWebResponse)req.GetResponse();                return DecodingResponse(res);
            }
            catch (Exception ex)
            {
                return string.Empty;
            }
        }