[转发]HttpWebRequest模拟登陆,存储Cookie以便登录请求后使用
2016-03-02 15:41
981 查看
转自/article/6222987.html
PostLogin :登录,并保存Cookie
PostRequest :登录后使用Cookie进行其他操作
PostLogin :登录,并保存Cookie
public static string PostLogin(string postData, string requestUrlString, ref CookieContainer cookie) { ASCIIEncoding encoding = new ASCIIEncoding(); byte[] data = encoding.GetBytes(postData); //向服务端请求 HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(requestUrlString); myRequest.Method = "POST"; myRequest.ContentType = "application/x-www-form-urlencoded"; myRequest.ContentLength = data.Length; myRequest.CookieContainer = new CookieContainer(); Stream newStream = myRequest.GetRequestStream(); newStream.Write(data, 0, data.Length); newStream.Close(); //将请求的结果发送给客户端(界面、应用) HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse(); cookie.Add(myResponse.Cookies); StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8); return reader.ReadToEnd(); }
PostRequest :登录后使用Cookie进行其他操作
public static string PostRequest(string postData, string requestUrlString, CookieContainer cookie) { ASCIIEncoding encoding = new ASCIIEncoding(); byte[] data = encoding.GetBytes(postData); HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(requestUrlString); myRequest.Method = "POST"; myRequest.ContentType = "application/x-www-form-urlencoded"; myRequest.ContentLength = data.Length; myRequest.CookieContainer = cookie; Stream newStream = myRequest.GetRequestStream(); newStream.Write(data, 0, data.Length); newStream.Close(); HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse(); StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8); return reader.ReadToEnd(); }
相关文章推荐
- 20个你可能不知道的 Linux 网络工具
- iOS网络开发(6)网络图片加载开源框架SDWebImage
- HttpClient 4使用方法的几个例子
- httpclient 3上传文件例子
- HttpClient4登陆有验证码的网站
- HttpClient4登陆有验证码的网站
- Eclipse和Tomcat联合进行网络编程的环境搭建
- iOS网络开发(5)请求的缓存
- 网络互联参考模型
- iOS学习----------AFNetworking(1)网络监控
- HTTP Content-type 对照表
- 转 https://www.zhihu.com/question/27606493/answer/37447829
- Linux学习笔记之网络管理
- Http get和post的区别
- 低功耗广域网络中的LoRa技术
- iOS网络开发(4)网络数据加密
- iOS开发网络数据之AFNetworking使用
- 移动客户端网络优化
- linux下如何配置TCP参数设置详解
- iOS 的 TCP/IP 协议族剖析 && Socket