带CookieContainer进行post
1.获取CookieContainer ——用户登录
CookieContainer cookie = new CookieContainer();
UserLoginPost("post地址", "参数", ref cookie, "utf-8");
void UserLoginPost(string Url, string postDataStr, ref CookieContainer cookie1, string EncodingType)
{
HttpWebRequest request1 = (HttpWebRequest)WebRequest.Create(Url);
if (cookie1.Count == 0)
{
request1.CookieContainer = new CookieContainer();
cookie1 = request1.CookieContainer;
}
else
{
request1.CookieContainer = cookie1;
}
byte[] postData = Encoding.GetEncoding(EncodingType).GetBytes(postDataStr);
request1.Method = "POST";
request1.KeepAlive = false;
request1.AllowAutoRedirect = true;
request1.ContentType = "application/x-www-form-urlencoded";
request1.ContentLength = postData.Length;
request1.Referer = Url;
request1.UserAgent = "Mozilla/5.0 (Windows NT 5.2; rv:14.0) Gecko/20100101 Firefox/14.0.1";
//提交
Stream myRequestStream = request1.GetRequestStream();
myRequestStream.Write(postData, 0, postData.Length);
myRequestStream.Dispose();
myRequestStream.Close();
//获取信息
HttpWebResponse response1 = (HttpWebResponse)request1.GetResponse();
response1.Cookies = cookie1.GetCookies(request1.RequestUri);//获取一个包含url的Cookie集合的CookieCollection
Stream myResponseStream = response1.GetResponseStream();
StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding(EncodingType));
string retString = myStreamReader.ReadToEnd();
myStreamReader.Close();
myResponseStream.Close();
}
2.保存CookieContainer到txt里
public List<Cookie> GetAllCookies(CookieContainer cc)
{
List<Cookie> lstCookies = new List<Cookie>();
Hashtable table = (Hashtable)cc.GetType().InvokeMember("m_domainTable",
System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.GetField |
System.Reflection.BindingFlags.Instance, null, cc, new object[] { });
foreach (object pathList in table.Values)
{
SortedList lstCookieCol = (SortedList)pathList.GetType().InvokeMember("m_list",
System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.GetField
| System.Reflection.BindingFlags.Instance, null, pathList, new object[] { });
foreach (CookieCollection colCookies in lstCookieCol.Values)
foreach (Cookie c in colCookies) lstCookies.Add(c);
}
return lstCookies;
}
public string CookieContainerToString(CookieContainer cc)
{
StringBuilder sbc = new StringBuilder();
List<Cookie> cooklist = GetAllCookies(cc);
foreach (Cookie cookie in cooklist)
{
sbc.AppendFormat("{0};{1};{2};{3};{4};{5}\r\n",
cookie.Domain, cookie.Name, cookie.Path, cookie.Port,
cookie.Secure.ToString(), cookie.Value);
}
return sbc.ToString();
}
FileStream fs = File.Create("E:\\caijiPerson\\ajax\\jianli.txt");
fs.Close();
File.WriteAllText("E:\\caijiPerson\\ajax\\jianli.txt", CookieContainerToString(cookie), System.Text.Encoding.Default);
3.读取txt里的cookie
//读取txt里的cookie 第一种方法
string[] cookies = File.ReadAllText("E:\\caijiPerson\\ajax\\jianli.txt", System.Text.Encoding.Default).Split("\r\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
//读取txt里的cookie 第2种方法
StreamReader sr = new StreamReader(System.Web.HttpContext.Current.Server.MapPath("ajax/jianli.txt"), System.Text.Encoding.Default);
string input = sr.ReadToEnd();
sr.Close();
string[] cookies = Regex.Split(input, "\r\n", RegexOptions.IgnoreCase);
//
string cookieString = changeCookieForSend(cookies);
public string changeCookieForSend(string[] cookies)
{
string sendCookie = "";
foreach (string c in cookies)
{
string[] cc = c.Split(";".ToCharArray());
Cookie ck = new Cookie(); ;
ck.Discard = false;
ck.Domain = cc[0];
ck.Expired = true;
ck.HttpOnly = true;
ck.Name = cc[1];
ck.Path = cc[2];
ck.Port = cc[3];
ck.Secure = bool.Parse(cc[4]);
ck.Value = cc[5];
sendCookie += ck.Name + "=" + ck.Value + ";";
}
return sendCookie;
}
4.带上cookie字符串去post
string cookieString = changeCookieForSend(cookies);
html = GetPostData("post地址", "utf-8", cookieString);
string GetPostData(string url, string encodeType, string cookieString)
{
request = (HttpWebRequest)HttpWebRequest.Create(url); //创建一个请求示例
//本来4.0以下的使用 request.CookieContainer = CookieContainer;
//4.0以上的包括4.0用下面的字符串形式
request.Headers["Cookie"] = cookieString;//net4.0以上的有一个bug,所以用这个cookie字符串的格式来实现
request.Method = "GET";
request.Host = "jianli.tzrl.com";
request.KeepAlive = true;
request.AllowAutoRedirect = true;
request.ContentType = "application/x-www-form-urlencoded";
request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
request.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2; Trident/4.0; QQDownload 717; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
response = (HttpWebResponse)request.GetResponse(); //获取响应,即发送请求
//response.Cookies = cookie1.GetCookies(request.RequestUri);//获取一个包含url的Cookie集合的CookieCollection
Stream responseStream = response.GetResponseStream();
StreamReader streamReader = new StreamReader(responseStream, Encoding.GetEncoding(encodeType));
string html = streamReader.ReadToEnd();
return html;
}
带CookieContainer进行post的更多相关文章
- 用HttpWebRequest提交带验证码的网站
using System; using System.Drawing; using System.IO; using System.Net; using System.Text; using Syst ...
- HttpHelps类,用来实现Http访问,Post或者Get方式的,直接访问,带Cookie的,带证书的等方式,可以设置代理
原文地址:http://blog.csdn.net/cdefg198/article/details/8315438 万能框架:http://www.sufeinet.com/forum.php?mo ...
- C# 模拟提交带附件(input type=file)的表单
今天调用某API时,对于文档中的传入参数:File[] 类型,感觉很陌生,无从下手! 按通常的方式在json参数中加入file的二进制数据提交,一直报错(参数错误)!后来经过多方咨询,是要换一种 表单 ...
- HttpHelpers类普通GET和POST方式,带Cookie和带证书验证模式
HttpHelpers类普通GET和POST方式,带Cookie和带证书验证模式 参考路径:https://www.cnblogs.com/splendidme/archive/2011/09/14/ ...
- C# 调用API接口处理公共类 自带JSON实体互转类
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net ...
- WPF带cookie get/post请求网页,下载文件,图片,可保持会话状态
直接写成啦一个MyNet.cs类方便使用 get/post方法请求 //get请求 MyNet.SendRequest("http://www.baidu.com"); //pos ...
- C#+HtmlAgilityPack+XPath带你采集数据(以采集天气数据为例子)
第一次接触HtmlAgilityPack是在5年前,一些意外,让我从技术部门临时调到销售部门,负责建立一些流程和寻找潜在客户,最后在阿里巴巴找到了很多客户信息,非常全面,刚开始是手动复制到Excel, ...
- 带你实现开发者头条APP(五)--RecyclerView下拉刷新上拉加载
title: 带你实现开发者头条APP(五)--RecyclerView下拉刷新上拉加载 tags: -RecyclerView,下拉刷新,上拉加载更多 grammar_cjkRuby: true - ...
- 带你实现开发者头条APP(四)---首页优化(加入design包)
title: 带你实现开发者头条APP(四)---首页优化(加入design包) tags: design,Toolbar,TabLayout,RecyclerView grammar_cjkRuby ...
随机推荐
- C#中的约束类型
- 解决SVN图标不显示问题
Windows最多只允许15个覆盖图标,它自己又用了几个,结果给用户用的就11个左右了,如果你安装了其他网盘,那可用的就更少了. 解决方法: 1.在运行里输入regedit进入注册表 2.依次打开HK ...
- 20170711筛选OutLook主题并转发
Sub 筛选OutLook主题并转发() On Error Resume Next Dim OutApp As Application Set OutApp = Application Dim Out ...
- Android之MVC模式的使用
MVC全名是Model View Controller,是模型(model)-视图(view)-控制器(controller)的缩写,一种软件设计典范,用一种业务逻辑.数据.界面显示分离的方法组织代码 ...
- AND Graph CodeForces - 987F (状压)
链接 大意:给定$m$个数, 若$x\&y=0$, 则在$x$与$y$之间连一条无向边. 求无向图的连通块个数 暴力连边显然超时的, 可以通过辅助结点优化连边, 复杂度$O(n2^n)$ #i ...
- consumer的DubboResponseTimeoutScanTimer线程
考虑这样一种情况,由于网络延时,consumer先抛出超时异常,一段时间后又收到了已经超时的响应,dubbo是怎么处理的? 拆分为3步看: 1. consumer的DubboResponseTimeo ...
- wordpress 使用less 样式无法及时刷新
wordpress 样式无法及时刷新 wordpress编写style样式时,无法及时刷新页面,因此特意记录一番如何处理较好,网友的建议清除Chrome缓存,实时修改style携带的参数 折腾之旅开启 ...
- 文件的移动,删除 rename remove unlink 函数
int rename(const char *oldpath, const char *newpath); rename() renames a file, moving it between ...
- JavaScript学习总结(十)——this关键字
1 <script type="text/javascript"> 2 function Person(){ 3 /*使用var 属性名定义的属性是类的私有属性,外界无 ...
- POJ 1847 Floyd_wshall算法
前面用dijstra写过了.但是捏.数据很小.也可以用Floyd来写. 注意题目里给出的是有向的权值. 附代码:#include<stdio.h>#include<string.h& ...