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}
",
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(" ".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, "
", 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;
}