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的更多相关文章

  1. 用HttpWebRequest提交带验证码的网站

    using System; using System.Drawing; using System.IO; using System.Net; using System.Text; using Syst ...

  2. HttpHelps类,用来实现Http访问,Post或者Get方式的,直接访问,带Cookie的,带证书的等方式,可以设置代理

    原文地址:http://blog.csdn.net/cdefg198/article/details/8315438 万能框架:http://www.sufeinet.com/forum.php?mo ...

  3. C# 模拟提交带附件(input type=file)的表单

    今天调用某API时,对于文档中的传入参数:File[] 类型,感觉很陌生,无从下手! 按通常的方式在json参数中加入file的二进制数据提交,一直报错(参数错误)!后来经过多方咨询,是要换一种 表单 ...

  4. HttpHelpers类普通GET和POST方式,带Cookie和带证书验证模式

    HttpHelpers类普通GET和POST方式,带Cookie和带证书验证模式 参考路径:https://www.cnblogs.com/splendidme/archive/2011/09/14/ ...

  5. C# 调用API接口处理公共类 自带JSON实体互转类

    using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net ...

  6. WPF带cookie get/post请求网页,下载文件,图片,可保持会话状态

    直接写成啦一个MyNet.cs类方便使用 get/post方法请求 //get请求 MyNet.SendRequest("http://www.baidu.com"); //pos ...

  7. C#+HtmlAgilityPack+XPath带你采集数据(以采集天气数据为例子)

    第一次接触HtmlAgilityPack是在5年前,一些意外,让我从技术部门临时调到销售部门,负责建立一些流程和寻找潜在客户,最后在阿里巴巴找到了很多客户信息,非常全面,刚开始是手动复制到Excel, ...

  8. 带你实现开发者头条APP(五)--RecyclerView下拉刷新上拉加载

    title: 带你实现开发者头条APP(五)--RecyclerView下拉刷新上拉加载 tags: -RecyclerView,下拉刷新,上拉加载更多 grammar_cjkRuby: true - ...

  9. 带你实现开发者头条APP(四)---首页优化(加入design包)

    title: 带你实现开发者头条APP(四)---首页优化(加入design包) tags: design,Toolbar,TabLayout,RecyclerView grammar_cjkRuby ...

随机推荐

  1. 机器学习 Matplotlib库入门

    2017-07-21 15:22:05 Matplotlib库是一个优秀的python的数据可视化的第三方类库,其中的pyplot支持了类似matlab的图像输出操作.matplotlib.pyplo ...

  2. PyQt5-GUI生成随机生成小工具

    自己修改了代码:实现了自动生成SSN,手机号和姓名的功能 import sys from PyQt5.QtGui import * from PyQt5.QtWidgets import * from ...

  3. Illumina Sequence Identifiers 序列标识符 index详解

    大家基本都知道什么是 FASTA 和 FastQ 格式了,但这是不够的. 我们还需要了解世界上最大的测序公司自己定制的 FastQ 格式,因为你可能会经常用到,有时还会亲自去处理它们. 本文主题:Il ...

  4. 12月12日 has_many through:的interference, option

    has_many :products, through: :cart_items, source: :product build定义:collection.build(attributes = {}, ...

  5. codeforces 568a//Primes or Palindromes?// Codeforces Round #315 (Div. 1)

    题意:求使pi(n)*q<=rub(n)*p成立的最大的n. 先收集所有的质数和回文数.质数好搜集.回文数奇回文就0-9的数字,然后在头尾添加一个数.在x前后加a,就是x*10+a+a*pow( ...

  6. java.lang.UnsupportedClassVersionError: com/my/test/TestUser : Unsupported major.minor version 52.0

    问题原因: 1.执行代码的jdk版本 低于 编译的jdk版本 2.项目用JDK1.8运行过,现在又在本地的eclipse等开发工具或者本地环境变量为低版本的jdk1.7或者jdk1.6下运行,ecli ...

  7. Executors类的newFixedThreadPool, newCachedThreadPool, newScheduledThreadPool

    Executors 类对 ThreadPoolExecutor 的构造函数进行了封装,使用该类可方便地创建线程池. 1. newFixedThreadPool public static Execut ...

  8. elasticsearch 自定义_id

    elasticsearch 自定义ID: curl -s -XPUT localhost:9200/web -d ' { "mappings": { "blog" ...

  9. linux和window是文件挂载

    1. 首先在windows下面创建share文件夹并设置共享(右键->属性->共享)2. 确认ubuntu安装了mount.cifs,apt-get install mount.cifs ...

  10. learning docker steps(3) ----- docker services 初次体验

    参考:https://docs.docker.com/get-started/part3/#docker-composeyml docker 的 service样例, 我们可以理解成是一个本地负载均衡 ...