c# 模拟登陆(带验证码) c# 使用 HttpWebRequest模拟登陆(附带验证码)

近来发现这个挺有用,从网上搜集过来一系列,参考参考。

c# 使用 HttpWebRequest模拟登陆(附带验证码)

在C#中,可以使用HttpWebRequest进行相关的模拟登陆,登陆后进行相关的操作,比如抓取数据,页面分析,制作相关登陆助手等等。

先说下流程

1.使用httpwebrequest先进入你要登录的网站,获取cookie

2.使用第一步获取的cookie到验证码的网页将验证码下载下来。

3.使用Post数据 发送至网站。如果有cookie则继续保存。

4.使用第三步的cookie登陆相关网页操作。

获取相关数据可以使用抓包工具进行抓取,如httpwatch。(网上下载的好多都有病毒,下载的时候注意点)

1。

  1. ///<summary>
  2. ///通过get方式请求页面,传递一个实例化的cookieContainer
  3. ///</summary>
  4. ///<paramname="postUrl"></param>
  5. ///<paramname="cookie"></param>
  6. ///<returns></returns>
  7. publicstaticArrayListGetHtmlData(stringpostUrl,CookieContainercookie)
  8. {
  9. HttpWebRequestrequest;
  10. HttpWebResponseresponse;
  11. ArrayListlist=newArrayList();
  12. request=WebRequest.Create(postUrl)asHttpWebRequest;
  13. request.Method="GET";
  14. request.UserAgent="Mozilla/4.0";
  15. request.CookieContainer=cookie;
  16. request.KeepAlive=true;
  17. request.CookieContainer=cookie;
  18. try
  19. {
  20. //获取服务器返回的资源
  21. using(response=(HttpWebResponse)request.GetResponse())
  22. {
  23. using(StreamReaderreader=newStreamReader(response.GetResponseStream(),Encoding.Default))
  24. {
  25. cookie.Add(response.Cookies);
  26. //保存Cookies
  27. list.Add(cookie);
  28. list.Add(reader.ReadToEnd());
  29. list.Add(Guid.NewGuid().ToString());//图片名
  30. }
  31. }
  32. }
  33. catch(WebExceptionex)
  34. {
  35. list.Clear();
  36. list.Add("发生异常/n/r");
  37. WebResponsewr=ex.Response;
  38. using(Streamst=wr.GetResponseStream())
  39. {
  40. using(StreamReadersr=newStreamReader(st,System.Text.Encoding.Default))
  41. {
  42. list.Add(sr.ReadToEnd());
  43. }
  44. }
  45. }
  46. catch(Exceptionex)
  47. {
  48. list.Clear();
  49. list.Add("5");
  50. list.Add("发生异常:"+ex.Message);
  51. }
  52. returnlist;
  53. }
/// <summary> /// 通过get方式请求页面,传递一个实例化的cookieContainer /// </summary> /// <param name="postUrl"></param> /// <param name="cookie"></param> /// <returns></returns> public static ArrayList GetHtmlData(string postUrl, CookieContainer cookie) { HttpWebRequest request; HttpWebResponse response; ArrayList list = new ArrayList(); request = WebRequest.Create(postUrl) as HttpWebRequest; request.Method = "GET"; request.UserAgent = "Mozilla/4.0"; request.CookieContainer = cookie; request.KeepAlive = true; request.CookieContainer = cookie; try { //获取服务器返回的资源 using (response = (HttpWebResponse)request.GetResponse()) { using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.Default)) { cookie.Add(response.Cookies); //保存Cookies list.Add(cookie); list.Add(reader.ReadToEnd()); list.Add(Guid.NewGuid().ToString());//图片名 } } } catch (WebException ex) { list.Clear(); list.Add("发生异常/n/r"); WebResponse wr = ex.Response; using (Stream st = wr.GetResponseStream()) { using (StreamReader sr = new StreamReader(st, System.Text.Encoding.Default)) { list.Add(sr.ReadToEnd()); } } } catch (Exception ex) { list.Clear(); list.Add("5"); list.Add("发生异常:" + ex.Message); } return list; }

2.下载验证码,保存在本地。

  1. ///<summary>
  2. ///下载验证码图片并保存到本地
  3. ///</summary>
  4. ///<paramname="Url">验证码URL</param>
  5. ///<paramname="cookCon">Cookies值</param>
  6. ///<paramname="savePath">保存位置/文件名</param>
  7. publicstaticboolDowloadCheckImg(stringUrl,CookieContainercookCon,stringsavePath)
  8. {
  9. boolbol=true;
  10. HttpWebRequestwebRequest=(HttpWebRequest)WebRequest.Create(Url);
  11. //属性配置
  12. webRequest.AllowWriteStreamBuffering=true;
  13. webRequest.Credentials=System.Net.CredentialCache.DefaultCredentials;
  14. webRequest.MaximumResponseHeadersLength=-1;
  15. webRequest.Accept="image/gif,image/x-xbitmap,image/jpeg,image/pjpeg,application/x-shockwave-flash,application/vnd.ms-excel,application/vnd.ms-powerpoint,application/msword,*/*";
  16. webRequest.UserAgent="Mozilla/4.0(compatible;MSIE6.0;WindowsNT5.1;SV1;Maxthon;.NETCLR1.1.4322)";
  17. webRequest.ContentType="application/x-www-form-urlencoded";
  18. webRequest.Method="GET";
  19. webRequest.Headers.Add("Accept-Language","zh-cn");
  20. webRequest.Headers.Add("Accept-Encoding","gzip,deflate");
  21. webRequest.KeepAlive=true;
  22. webRequest.CookieContainer=cookCon;
  23. try
  24. {
  25. //获取服务器返回的资源
  26. using(HttpWebResponsewebResponse=(HttpWebResponse)webRequest.GetResponse())
  27. {
  28. using(Streamsream=webResponse.GetResponseStream())
  29. {
  30. List<byte>list=newList<byte>();
  31. while(true)
  32. {
  33. intdata=sream.ReadByte();
  34. if(data==-1)
  35. break;
  36. list.Add((byte)data);
  37. }
  38. File.WriteAllBytes(savePath,list.ToArray());
  39. }
  40. }
  41. }
  42. catch(WebExceptionex)
  43. {
  44. bol=false;
  45. }
  46. catch(Exceptionex)
  47. {
  48. bol=false;
  49. }
  50. returnbol;
  51. }
/// <summary> /// 下载验证码图片并保存到本地 /// </summary> /// <param name="Url">验证码URL</param> /// <param name="cookCon">Cookies值</param> /// <param name="savePath">保存位置/文件名</param> public static bool DowloadCheckImg(string Url, CookieContainer cookCon, string savePath) { bool bol = true; HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(Url); //属性配置 webRequest.AllowWriteStreamBuffering = true; webRequest.Credentials = System.Net.CredentialCache.DefaultCredentials; webRequest.MaximumResponseHeadersLength = -1; webRequest.Accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*"; webRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; Maxthon; .NET CLR 1.1.4322)"; webRequest.ContentType = "application/x-www-form-urlencoded"; webRequest.Method = "GET"; webRequest.Headers.Add("Accept-Language", "zh-cn"); webRequest.Headers.Add("Accept-Encoding", "gzip,deflate"); webRequest.KeepAlive = true; webRequest.CookieContainer = cookCon; try { //获取服务器返回的资源 using (HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse()) { using (Stream sream = webResponse.GetResponseStream()) { List<byte> list = new List<byte>(); while (true) { int data = sream.ReadByte(); if (data == -1) break; list.Add((byte)data); } File.WriteAllBytes(savePath, list.ToArray()); } } } catch (WebException ex) { bol = false; } catch (Exception ex) { bol = false; } return bol; }

3。发送post数据

  1. ///<summary>
  2. ///发送相关数据至页面
  3. ///进行登录操作
  4. ///并保存cookie
  5. ///</summary>
  6. ///<paramname="postData"></param>
  7. ///<paramname="postUrl"></param>
  8. ///<paramname="cookie"></param>
  9. ///<returns></returns>
  10. publicstaticArrayListPostData(stringpostData,stringpostUrl,CookieContainercookie)
  11. {
  12. ArrayListlist=newArrayList();
  13. HttpWebRequestrequest;
  14. HttpWebResponseresponse;
  15. ASCIIEncodingencoding=newASCIIEncoding();
  16. request=WebRequest.Create(postUrl)asHttpWebRequest;
  17. byte[]b=encoding.GetBytes(postData);
  18. request.UserAgent="Mozilla/4.0";
  19. request.Method="POST";
  20. request.CookieContainer=cookie;
  21. request.ContentLength=b.Length;
  22. using(Streamstream=request.GetRequestStream())
  23. {
  24. stream.Write(b,0,b.Length);
  25. }
  26. try
  27. {
  28. //获取服务器返回的资源
  29. using(response=request.GetResponse()asHttpWebResponse)
  30. {
  31. using(StreamReaderreader=newStreamReader(response.GetResponseStream(),Encoding.UTF8))
  32. {
  33. if(response.Cookies.Count>0)
  34. cookie.Add(response.Cookies);
  35. list.Add(cookie);
  36. list.Add(reader.ReadToEnd());
  37. }
  38. }
  39. }
  40. catch(WebExceptionwex)
  41. {
  42. WebResponsewr=wex.Response;
  43. using(Streamst=wr.GetResponseStream())
  44. {
  45. using(StreamReadersr=newStreamReader(st,System.Text.Encoding.Default))
  46. {
  47. list.Add(sr.ReadToEnd());
  48. }
  49. }
  50. }
  51. catch(Exceptionex)
  52. {
  53. list.Add("发生异常/n/r"+ex.Message);
  54. }
  55. returnlist;
  56. }
/// <summary> /// 发送相关数据至页面 /// 进行登录操作 /// 并保存cookie /// </summary> /// <param name="postData"></param> /// <param name="postUrl"></param> /// <param name="cookie"></param> /// <returns></returns> public static ArrayList PostData(string postData, string postUrl, CookieContainer cookie) { ArrayList list = new ArrayList(); HttpWebRequest request; HttpWebResponse response; ASCIIEncoding encoding = new ASCIIEncoding(); request = WebRequest.Create(postUrl) as HttpWebRequest; byte[] b = encoding.GetBytes(postData); request.UserAgent = "Mozilla/4.0"; request.Method = "POST"; request.CookieContainer = cookie; request.ContentLength = b.Length; using (Stream stream = request.GetRequestStream()) { stream.Write(b, 0, b.Length); } try { //获取服务器返回的资源 using (response = request.GetResponse() as HttpWebResponse) { using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8)) { if (response.Cookies.Count > 0) cookie.Add(response.Cookies); list.Add(cookie); list.Add(reader.ReadToEnd()); } } } catch (WebException wex) { WebResponse wr = wex.Response; using (Stream st = wr.GetResponseStream()) { using (StreamReader sr = new StreamReader(st, System.Text.Encoding.Default)) { list.Add(sr.ReadToEnd()); } } } catch (Exception ex) { list.Add("发生异常/n/r"+ex.Message); } return list; }

4。就是第三步请求的链接地址换一个就行了

好了

以上核心代码已经贴出了

具体实现需要靠你们按照你们自己的逻辑

作者还说:

还有一些header能不写就不写,因为2天前一直在获取返回response这地方报500错误。

找了N多代码,看了N多资料都不可以。最后将一些header注释掉就可以了,真郁闷。

我马上试验,等有做出成熟的例子,再写新文章提供给大家!

在C#中,可以使用HttpWebRequest进行相关的模拟登陆,登陆后进行相关的操作,比如抓取数据,页面分析,制作相关登陆助手等等。

先说下流程

1.使用httpwebrequest先进入你要登录的网站,获取cookie

2.使用第一步获取的cookie到验证码的网页将验证码下载下来。

3.使用Post数据 发送至网站。如果有cookie则继续保存。

4.使用第三步的cookie登陆相关网页操作。

获取相关数据可以使用抓包工具进行抓取,如httpwatch。(网上下载的好多都有病毒,下载的时候注意点)

1。

  1. ///<summary>
  2. ///通过get方式请求页面,传递一个实例化的cookieContainer
  3. ///</summary>
  4. ///<paramname="postUrl"></param>
  5. ///<paramname="cookie"></param>
  6. ///<returns></returns>
  7. publicstaticArrayListGetHtmlData(stringpostUrl,CookieContainercookie)
  8. {
  9. HttpWebRequestrequest;
  10. HttpWebResponseresponse;
  11. ArrayListlist=newArrayList();
  12. request=WebRequest.Create(postUrl)asHttpWebRequest;
  13. request.Method="GET";
  14. request.UserAgent="Mozilla/4.0";
  15. request.CookieContainer=cookie;
  16. request.KeepAlive=true;
  17. request.CookieContainer=cookie;
  18. try
  19. {
  20. //获取服务器返回的资源
  21. using(response=(HttpWebResponse)request.GetResponse())
  22. {
  23. using(StreamReaderreader=newStreamReader(response.GetResponseStream(),Encoding.Default))
  24. {
  25. cookie.Add(response.Cookies);
  26. //保存Cookies
  27. list.Add(cookie);
  28. list.Add(reader.ReadToEnd());
  29. list.Add(Guid.NewGuid().ToString());//图片名
  30. }
  31. }
  32. }
  33. catch(WebExceptionex)
  34. {
  35. list.Clear();
  36. list.Add("发生异常/n/r");
  37. WebResponsewr=ex.Response;
  38. using(Streamst=wr.GetResponseStream())
  39. {
  40. using(StreamReadersr=newStreamReader(st,System.Text.Encoding.Default))
  41. {
  42. list.Add(sr.ReadToEnd());
  43. }
  44. }
  45. }
  46. catch(Exceptionex)
  47. {
  48. list.Clear();
  49. list.Add("5");
  50. list.Add("发生异常:"+ex.Message);
  51. }
  52. returnlist;
  53. }
/// <summary> /// 通过get方式请求页面,传递一个实例化的cookieContainer /// </summary> /// <param name="postUrl"></param> /// <param name="cookie"></param> /// <returns></returns> public static ArrayList GetHtmlData(string postUrl, CookieContainer cookie) { HttpWebRequest request; HttpWebResponse response; ArrayList list = new ArrayList(); request = WebRequest.Create(postUrl) as HttpWebRequest; request.Method = "GET"; request.UserAgent = "Mozilla/4.0"; request.CookieContainer = cookie; request.KeepAlive = true; request.CookieContainer = cookie; try { //获取服务器返回的资源 using (response = (HttpWebResponse)request.GetResponse()) { using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.Default)) { cookie.Add(response.Cookies); //保存Cookies list.Add(cookie); list.Add(reader.ReadToEnd()); list.Add(Guid.NewGuid().ToString());//图片名 } } } catch (WebException ex) { list.Clear(); list.Add("发生异常/n/r"); WebResponse wr = ex.Response; using (Stream st = wr.GetResponseStream()) { using (StreamReader sr = new StreamReader(st, System.Text.Encoding.Default)) { list.Add(sr.ReadToEnd()); } } } catch (Exception ex) { list.Clear(); list.Add("5"); list.Add("发生异常:" + ex.Message); } return list; }

2.下载验证码,保存在本地。

  1. ///<summary>
  2. ///下载验证码图片并保存到本地
  3. ///</summary>
  4. ///<paramname="Url">验证码URL</param>
  5. ///<paramname="cookCon">Cookies值</param>
  6. ///<paramname="savePath">保存位置/文件名</param>
  7. publicstaticboolDowloadCheckImg(stringUrl,CookieContainercookCon,stringsavePath)
  8. {
  9. boolbol=true;
  10. HttpWebRequestwebRequest=(HttpWebRequest)WebRequest.Create(Url);
  11. //属性配置
  12. webRequest.AllowWriteStreamBuffering=true;
  13. webRequest.Credentials=System.Net.CredentialCache.DefaultCredentials;
  14. webRequest.MaximumResponseHeadersLength=-1;
  15. webRequest.Accept="image/gif,image/x-xbitmap,image/jpeg,image/pjpeg,application/x-shockwave-flash,application/vnd.ms-excel,application/vnd.ms-powerpoint,application/msword,*/*";
  16. webRequest.UserAgent="Mozilla/4.0(compatible;MSIE6.0;WindowsNT5.1;SV1;Maxthon;.NETCLR1.1.4322)";
  17. webRequest.ContentType="application/x-www-form-urlencoded";
  18. webRequest.Method="GET";
  19. webRequest.Headers.Add("Accept-Language","zh-cn");
  20. webRequest.Headers.Add("Accept-Encoding","gzip,deflate");
  21. webRequest.KeepAlive=true;
  22. webRequest.CookieContainer=cookCon;
  23. try
  24. {
  25. //获取服务器返回的资源
  26. using(HttpWebResponsewebResponse=(HttpWebResponse)webRequest.GetResponse())
  27. {
  28. using(Streamsream=webResponse.GetResponseStream())
  29. {
  30. List<byte>list=newList<byte>();
  31. while(true)
  32. {
  33. intdata=sream.ReadByte();
  34. if(data==-1)
  35. break;
  36. list.Add((byte)data);
  37. }
  38. File.WriteAllBytes(savePath,list.ToArray());
  39. }
  40. }
  41. }
  42. catch(WebExceptionex)
  43. {
  44. bol=false;
  45. }
  46. catch(Exceptionex)
  47. {
  48. bol=false;
  49. }
  50. returnbol;
  51. }
/// <summary> /// 下载验证码图片并保存到本地 /// </summary> /// <param name="Url">验证码URL</param> /// <param name="cookCon">Cookies值</param> /// <param name="savePath">保存位置/文件名</param> public static bool DowloadCheckImg(string Url, CookieContainer cookCon, string savePath) { bool bol = true; HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(Url); //属性配置 webRequest.AllowWriteStreamBuffering = true; webRequest.Credentials = System.Net.CredentialCache.DefaultCredentials; webRequest.MaximumResponseHeadersLength = -1; webRequest.Accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*"; webRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; Maxthon; .NET CLR 1.1.4322)"; webRequest.ContentType = "application/x-www-form-urlencoded"; webRequest.Method = "GET"; webRequest.Headers.Add("Accept-Language", "zh-cn"); webRequest.Headers.Add("Accept-Encoding", "gzip,deflate"); webRequest.KeepAlive = true; webRequest.CookieContainer = cookCon; try { //获取服务器返回的资源 using (HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse()) { using (Stream sream = webResponse.GetResponseStream()) { List<byte> list = new List<byte>(); while (true) { int data = sream.ReadByte(); if (data == -1) break; list.Add((byte)data); } File.WriteAllBytes(savePath, list.ToArray()); } } } catch (WebException ex) { bol = false; } catch (Exception ex) { bol = false; } return bol; }

3。发送post数据

  1. ///<summary>
  2. ///发送相关数据至页面
  3. ///进行登录操作
  4. ///并保存cookie
  5. ///</summary>
  6. ///<paramname="postData"></param>
  7. ///<paramname="postUrl"></param>
  8. ///<paramname="cookie"></param>
  9. ///<returns></returns>
  10. publicstaticArrayListPostData(stringpostData,stringpostUrl,CookieContainercookie)
  11. {
  12. ArrayListlist=newArrayList();
  13. HttpWebRequestrequest;
  14. HttpWebResponseresponse;
  15. ASCIIEncodingencoding=newASCIIEncoding();
  16. request=WebRequest.Create(postUrl)asHttpWebRequest;
  17. byte[]b=encoding.GetBytes(postData);
  18. request.UserAgent="Mozilla/4.0";
  19. request.Method="POST";
  20. request.CookieContainer=cookie;
  21. request.ContentLength=b.Length;
  22. using(Streamstream=request.GetRequestStream())
  23. {
  24. stream.Write(b,0,b.Length);
  25. }
  26. try
  27. {
  28. //获取服务器返回的资源
  29. using(response=request.GetResponse()asHttpWebResponse)
  30. {
  31. using(StreamReaderreader=newStreamReader(response.GetResponseStream(),Encoding.UTF8))
  32. {
  33. if(response.Cookies.Count>0)
  34. cookie.Add(response.Cookies);
  35. list.Add(cookie);
  36. list.Add(reader.ReadToEnd());
  37. }
  38. }
  39. }
  40. catch(WebExceptionwex)
  41. {
  42. WebResponsewr=wex.Response;
  43. using(Streamst=wr.GetResponseStream())
  44. {
  45. using(StreamReadersr=newStreamReader(st,System.Text.Encoding.Default))
  46. {
  47. list.Add(sr.ReadToEnd());
  48. }
  49. }
  50. }
  51. catch(Exceptionex)
  52. {
  53. list.Add("发生异常/n/r"+ex.Message);
  54. }
  55. returnlist;
  56. }
/// <summary> /// 发送相关数据至页面 /// 进行登录操作 /// 并保存cookie /// </summary> /// <param name="postData"></param> /// <param name="postUrl"></param> /// <param name="cookie"></param> /// <returns></returns> public static ArrayList PostData(string postData, string postUrl, CookieContainer cookie) { ArrayList list = new ArrayList(); HttpWebRequest request; HttpWebResponse response; ASCIIEncoding encoding = new ASCIIEncoding(); request = WebRequest.Create(postUrl) as HttpWebRequest; byte[] b = encoding.GetBytes(postData); request.UserAgent = "Mozilla/4.0"; request.Method = "POST"; request.CookieContainer = cookie; request.ContentLength = b.Length; using (Stream stream = request.GetRequestStream()) { stream.Write(b, 0, b.Length); } try { //获取服务器返回的资源 using (response = request.GetResponse() as HttpWebResponse) { using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8)) { if (response.Cookies.Count > 0) cookie.Add(response.Cookies); list.Add(cookie); list.Add(reader.ReadToEnd()); } } } catch (WebException wex) { WebResponse wr = wex.Response; using (Stream st = wr.GetResponseStream()) { using (StreamReader sr = new StreamReader(st, System.Text.Encoding.Default)) { list.Add(sr.ReadToEnd()); } } } catch (Exception ex) { list.Add("发生异常/n/r"+ex.Message); } return list; }

4。就是第三步请求的链接地址换一个就行了

好了

以上核心代码已经贴出了

具体实现需要靠你们按照你们自己的逻辑

作者还说:

还有一些header能不写就不写,因为2天前一直在获取返回response这地方报500错误。

找了N多代码,看了N多资料都不可以。最后将一些header注释掉就可以了,真郁闷。

我马上试验,等有做出成熟的例子,再写新文章提供给大家!

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值