使用C#发送Http请求实现模拟登陆实例

使用C#发送Http请求实现模拟登陆实例,第1张

概述模拟登陆的原理很简单,就是发送一个Http请求服务器获得响应,然后客户端获取到cookie即可实现模拟登陆,比如一些抢票软件的原理无非也是这样模拟客户端的cookie然后发送请求去抢票,然后12306本文将演示如何用C#来实

模拟登陆的原理很简单,就是发送一个http 请求服务器获得响应,然后客户端获取到cookie即可实现模拟登陆,比如一些抢票软件的原理无非也是这样模拟客户端的cookie 然后发送请求去抢票,然后12306 本文将演示如何用C# 来实现模拟登陆的,推荐一款工具fiddler,这是一款监听http 请求的利器。废话不多说,我就以博客园为例来实现模拟登陆。首先我登陆博客园 http://passport.cnblogs.com/login.aspx 输入用户名和密码点登陆 就会看到fiddler 上的相关信息:

Ok,我首先需要发送一个http 请求 ,这个请求时POST的方式,然后用户名和密码就是POST的数据。代码如下:

static cookieContainer Getcookie(string poststring,string postUrl) { cookieContainer cookie = new cookieContainer();  httpWebRequest httpRequset = (httpWebRequest)httpWebRequest.Create(postUrl);//创建http 请求httpRequset.cookieContainer = cookie;//设置cookiehttpRequset.Method = "POST";//POST 提交 httpRequset.KeepAlive = true; httpRequset.UserAgent = "Mozilla/5.0 (windows NT 6.3; WOW64; TrIDent/7.0; rv:11.0) like Gecko"; httpRequset.Accept = "text/HTML,application/xhtml+xml,*/*";httpRequset.ContentType = "application/x-www-form-urlencoded";//以上信息在监听请求的时候都有的直接复制过来byte[] bytes = System.Text.EnCoding.UTF8.GetBytes(poststring);httpRequset.ContentLength = bytes.Length; Stream stream = httpRequset.GetRequestStream();stream.Write(bytes,bytes.Length); stream.Close();//以上是POST数据的写入 httpWebResponse httpResponse = (httpWebResponse)httpRequset.GetResponse();//获得 服务端响应 return cookie;//拿到cookie }

 拿到cookie 之后我们就可以以用户的什么去用户的后台或者其他的地方:

 static string GetContent(cookieContainer cookie,string url){string content;httpWebRequest httpRequest = (httpWebRequest)httpWebRequest.Create(url);httpRequest.cookieContainer = cookie;httpRequest.Referer = url;httpRequest.UserAgent = "Mozilla/5.0 (windows NT 6.3; WOW64; TrIDent/7.0; rv:11.0) like Gecko";httpRequest.Accept = "text/HTML,*/*";httpRequest.ContentType = "application/x-www-form-urlencoded";httpRequest.Method = "GET";httpWebResponse httpResponse = (httpWebResponse)httpRequest.GetResponse();using (Stream responsestream = httpResponse.GetResponseStream()){ using (StreamReader sr = new StreamReader(responsestream,System.Text.EnCoding.UTF8)) { content = sr.ReadToEnd(); }} return content; }

 OK 下面是调用 我写的是一个控制台程序:

static voID Main(string[] args){string loginstr = "{要post 的登陆数据包括用户名和密码}";//从登陆的地址获取cookiecookieContainer cookie = Getcookie(loginstr,"http://passport.cnblogs.com/login.aspx"); //这个是进入后台地址 Console.Writeline(GetContent(cookie,"http://i.cnblogs.com/Editposts.aspx")); Console.Read();}

可以看到我已经进入了后台了:

如果我是没有登陆的情况下进入这个地址是这样的:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程小技巧。

总结

以上是内存溢出为你收集整理的使用C#发送Http请求实现模拟登陆实例全部内容,希望文章能够帮你解决使用C#发送Http请求实现模拟登陆实例所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://www.outofmemory.cn/langs/1257097.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-07
下一篇 2022-06-07

发表评论

登录后才能评论

评论列表(0条)

保存