c# 模拟登陆带验证码网站,思路是先请求验证码并记录cookie,登陆网站(请求的cookie用请求验证码保存的cookie),始终不能成功,提示未经授权。
请求验证码代码如下:
public static void GetCheckCode(string url, string path)
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.ServicePoint.Expect100Continue = false;
req.Method = "GET";
req.KeepAlive = true;
req.ContentType = "image/png";
req.CookieContainer = new CookieContainer();
HttpWebResponse rsp = (HttpWebResponse)req.GetResponse();
theCC = req.CookieContainer;
System.IO.Stream stream = null;
try
{
// 以字符流的方式读取HTTP响应
stream = rsp.GetResponseStream();
System.Drawing.Image.FromStream(stream).Save(path);
}
finally
{
// 释放资源
if (stream != null) stream.Close();
if (rsp != null) rsp.Close();
}
}
登陆主要代码如下:
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
//配置请求header
req.Headers.Add(HttpRequestHeader.AcceptCharset, "GBK,utf-8;q=0.7,*;q=0.3");
req.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate,sdch");
req.Headers.Add(HttpRequestHeader.AcceptLanguage, "zh-CN,zh;q=0.8");
req.Accept = "application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
req.KeepAlive = true;
req.Referer = referer;
req.Headers.Add(HttpRequestHeader.CacheControl, "max-age=0");
req.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.2; en-US) AppleWebKit/534.7 (KHTML, like Gecko) Chrome/7.0.517.5 Safari/534.7";
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.AllowAutoRedirect = true;
//设置cookieContainer用来接收cookie
req.CookieContainer = theCC;
//返回请求
res = (HttpWebResponse)req.GetResponse();