C# 带Cookies发送请求
#region --来自黄聪 void F1() { #region --创建cookies容器 添加Cookies和对应的URl(Hots主) CookieContainer cc = new CookieContainer(); //创建Cookie容器对象 (Cookies集合) cc.Add(new System.Uri("http://localhost:19720/"), new Cookie("Mxx", "UserName=admin&Pwd=123456")); // "Mxx为cookie名" #endregion //调用方法 来请求网址 string str = SendDataByPost("http://localhost:19720/Home/A1", "name=zhangsan&Pwd=123", ref cc); MessageBox.Show(str); } #region --同步通过POST方式发送数据 /// <summary> /// 通过POST方式发送数据 /// </summary> /// <param name="Url">url</param> /// <param name="postDataStr">Post数据</param> /// <param name="cookie">Cookie容器</param> /// <returns></returns> public string SendDataByPost(string Url, string postDataStr, ref CookieContainer cookie) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url); //请求地址 if (cookie.Count == 0) { request.CookieContainer = new CookieContainer(); //创建新的cookie容器对象 cookie = request.CookieContainer; // } else { request.CookieContainer = cookie; //设置请求的ecookes } request.Method = "POST"; //请求方式 request.ContentType = "application/x-www-form-urlencoded"; //请求的内容类型 request.ContentLength = postDataStr.Length; //请求内容长度 Stream myRequestStream = request.GetRequestStream(); //获取用于写入请求数据的流对象 【联网建立连接】 //写入流 StreamWriter myStreamWriter = new StreamWriter(myRequestStream, Encoding.GetEncoding("gb2312")); //使用GB2312编码写文件 myStreamWriter.Write(postDataStr); //将字符串写入流中 myStreamWriter.Close(); //关闭流写入对象 HttpWebResponse response = (HttpWebResponse)request.GetResponse(); //Response响应 //返回响应的资源 //读取流 Stream myResponseStream = response.GetResponseStream(); //获取流,该流用于读取来自服务器响应体 StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8")); //使用UTF-8编码读取文件 string retString = myStreamReader.ReadToEnd(); //读取流中的所有字符 myStreamReader.Close(); //关闭读取流对象 myResponseStream.Close(); //关闭当前流并释放与之关联的所有资源 return retString; } #endregion #region --同步通过GET方式发送数据 /// <summary> /// 通过GET方式发送数据 /// </summary> /// <param name="Url">url</param> /// <param name="postDataStr">GET数据</param> /// <param name="cookie">GET容器</param> /// <returns></returns> public string SendDataByGET(string Url, string postDataStr, ref CookieContainer cookie) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url + (postDataStr == "" ? "" : "?") + postDataStr); if (cookie.Count == 0) { request.CookieContainer = new CookieContainer(); cookie = request.CookieContainer; } else { request.CookieContainer = cookie; } request.Method = "GET"; request.ContentType = "text/html;charset=UTF-8"; HttpWebResponse response = (HttpWebResponse)request.GetResponse(); //Response响应 //返回响应的资源 Stream myResponseStream = response.GetResponseStream(); //获取服务器返回的流 StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));//使用utf-8编码读取文件 string retString = myStreamReader.ReadToEnd(); myStreamReader.Close(); myResponseStream.Close(); return retString; } #endregion private void Test() { string url = "http://i.baidu.com/"; string cookie = "PSINO=6;"; CookieContainer cc = new CookieContainer(); //创建cookie 容器对象 cc.SetCookies(new System.Uri(url), cookie); //将cookies指定的url string content = SendDataByGET(url, "", ref cc); Console.WriteLine(content); Console.ReadLine(); } #endregion
//-----------------------------
#region --哈希表的使用 public static Hashtable getCookieMap() { string sPath = "d:\\cookie.txt"; Hashtable maps = new Hashtable();//创建哈希表对象 FileStream fs = new FileStream(sPath, FileMode.Open); //文件流对象. StreamReader rf = new StreamReader(fs, System.Text.Encoding.GetEncoding("gb2312")); //读取cookie文本 string hm = ""; try { do { hm = rf.ReadLine(); } while (!rf.EndOfStream);//如果流当前流位置在结尾 结束循环 Console.WriteLine(hm); //输出 这个cookes文本中的字符串 String[] s1 = hm.Split(';'); //cookies文本中的字符串以 ";"号 分割 返回字符串数组 // Console.Write(s1.Length); for (int i = 0; i < s1.Length; i++) //遍历这个字符串数组 { int pos = s1[i].IndexOf('='); //查找到 字符 '=' 的位置 String value = s1[i].Substring(pos + 1);//从=号位置+1 开始截取到最后 String name = s1[i].Substring(0, pos); //从0开始截取到 = 号位置 name = name.Trim(); //移除字符串左右空白字符 //Console.WriteLine(name + ":" +value); maps.Add(name, value); //哈希表中添加数据 } } catch (Exception e) { Console.WriteLine("读取文件错误:" + e.Message); return null; } fs.Close(); //文件流关闭 rf.Close(); //流读取器 return maps; //返回这个哈希表对象 } //C#中遍历Hashtable的4种方法 static void testA() { Hashtable ht = new Hashtable(); ht.Add("1", "1111"); ht.Add("2", "2222"); ht.Add("3", "3333"); ht.Add("4", "4444"); //遍历方法一:遍历哈希表中的键 foreach (string key in ht.Keys) { //Console.WriteLine(string.Format("{0}-{1}"), key, ht[key]); Console.WriteLine(string.Format("{0}-{1}", key, ht[key])); } Console.WriteLine("**********************************************************"); //遍历方法二:遍历哈希表中的值 foreach (string value in ht.Values) { Console.WriteLine(value); } Console.WriteLine("**********************************************************"); //遍历方法三:遍历哈希表中的键值 foreach (DictionaryEntry de in ht) { Console.WriteLine(string.Format("{0}-{1}", de.Key, de.Value)); } Console.WriteLine("**********************************************************"); //遍历方法四:遍历哈希表中的键值 IDictionaryEnumerator myEnumerator = ht.GetEnumerator(); bool flag = myEnumerator.MoveNext(); while (flag) { Console.WriteLine(myEnumerator.Key + "-" + myEnumerator.Value); // Console.WriteLine(ht[myEnumerator.Key]);//ht[myEnumerator.Key]== myEnumerator.Value=true; flag = myEnumerator.MoveNext(); } Console.Read(); } #endregion //test(i + ":" + postStr.Substring(i * maxByte, maxByte), maps) //截取1024个字符 public static bool test(string str, Hashtable maps) { bool ok = false; string content = "{\"threadId\": \"39369\", \"groupId\": \"101419\", \"groupType\": \"3\", \"title\": \"code\", \"content\": \"" + str + "\"}"; //Console.WriteLine(content); string url = "http://home.cnblogs.com/WebService/GroupService.asmx/AddThreadComment"; //请求地址 string host = "http://home.cnblogs.com"; //主域名 try { byte[] bs = Encoding.ASCII.GetBytes(content); //获取内容转换为字节数组形式 HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url); req.Method = "POST"; req.ContentType = "application/json;charset=utf-8"; req.ContentLength = bs.Length; //cookies 容器 CookieContainer cc = new CookieContainer(); cc.Add(new Uri(host), new Cookie("cnzz_a1708446", maps["cnzz_a1708446"].ToString())); cc.Add(new Uri(host), new Cookie("ASP.NET_SessionId", maps["ASP.NET_SessionId"].ToString())); cc.Add(new Uri(host), new Cookie(".DottextCookie", maps[".DottextCookie"].ToString())); req.CookieContainer = cc; //设置这个连接cookie using (Stream reqStream = req.GetRequestStream()) //建立数据连接 { reqStream.Write(bs, 0, bs.Length);//向流中写入字节 序列 } StringBuilder sb = new StringBuilder(""); using (WebResponse wr = req.GetResponse()) //获得返回资源响应 { System.IO.Stream respStream = wr.GetResponseStream(); //返回的数据流 System.IO.StreamReader reader = new System.IO.StreamReader(respStream, System.Text.Encoding.GetEncoding("gb2312")); //读取返回的数据流 // int h = 0; string t = ""; do { t = reader.ReadLine(); //这个地方自己搞定吧,简单地写了一下成功与否 ok = true; } while (!reader.EndOfStream); //如果流当前流位置在结尾 结束循环 } return ok; } catch (Exception ex) { Console.WriteLine("异常在getPostRespone:" + ex.Source + ":" + ex.Message); return ok; } } static void Main(string[] args) { int maxByte = 1024; bool isDebug = false; if (args.Length >= 2) //测试 这段代码不会执行 { maxByte = Int32.Parse(args[0]); if (args[1] == "debug") //判断调试模式 isDebug = true; } Hashtable maps = getCookieMap(); //读取cookies文件返回哈希表 try { string sPath = "d:\\data.txt"; FileStream fs = new FileStream(sPath, FileMode.Open); StreamReader rf = new StreamReader(fs, System.Text.Encoding.GetEncoding("gb2312")); string postStr = ""; string temp; try { int i = 0; do { temp = rf.ReadLine(); postStr += temp; } while (!rf.EndOfStream); //读取发送post请求的数据 int len = postStr.Length; //字符串长度 for (i = 0; i < len / maxByte + 1; i++) //长度/1025 { if (i * maxByte + maxByte >= len) { //Console.WriteLine(postStr.Substring(i * maxByte, len - i * maxByte)); if (test(i + ":" + postStr.Substring(i * maxByte, len - i * maxByte), maps)) Console.WriteLine("post ok:" + i); if (isDebug) Console.ReadLine(); //这句话不执行 } else { //Console.WriteLine(postStr.Substring(i * maxByte, maxByte)); if (test(i + ":" + postStr.Substring(i * maxByte, maxByte), maps)) { Console.WriteLine("post ok:" + i); if (isDebug) Console.ReadLine(); //这句话不执行 } } } } catch (Exception e) { Console.WriteLine("读取文件错误:" + e.Message); return; } } catch (Exception ex) { Console.WriteLine(ex.Message + "----" + ex.Source); } Console.WriteLine("over!"); Console.ReadLine(); }