#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 == )
{
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 == )
{
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 = ; i < s1.Length; i++) //遍历这个字符串数组
{
int pos = s1[i].IndexOf('='); //查找到 字符 '=' 的位置
String value = s1[i].Substring(pos + );//从=号位置+1 开始截取到最后
String name = s1[i].Substring(, 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("", "");
ht.Add("", "");
ht.Add("", "");
ht.Add("", ""); //遍历方法一:遍历哈希表中的键
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, , 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 = ;
bool isDebug = false; if (args.Length >= ) //测试 这段代码不会执行
{
maxByte = Int32.Parse(args[]);
if (args[] == "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 = ;
do
{
temp = rf.ReadLine();
postStr += temp; }
while (!rf.EndOfStream); //读取发送post请求的数据
int len = postStr.Length; //字符串长度 for (i = ; i < len / maxByte + ; 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();
}

C# 带Cookies发送请求的更多相关文章

  1. python的requests库怎么发送带cookies的请求

     背景: 在用robot做接口自动化时,有一个查询接口需要用到登录后返回的token等信息作为cookies作为参数一起请求(token是在返回体中,并不在cookies中), 刚好create se ...

  2. 测试框架httpclent 3.获取cookie的信息,然后带cookies去发送请求

    在properties文件里面: startupWithCookies.json [ { "description":"这是一个会返回cookies信息的get请求&qu ...

  3. Python接口测试实战2 - 使用Python发送请求

    如有任何学习问题,可以添加作者微信:lockingfree 课程目录 Python接口测试实战1(上)- 接口测试理论 Python接口测试实战1(下)- 接口测试工具的使用 Python接口测试实战 ...

  4. Requests发送带cookies请求

    一.缘 起 最近学习[悠悠课堂]的接口自动化教程,文中提到Requests发送带cookies请求的方法,笔者随之也将其用于手头实际项目中,大致如下 二.背 景 实际需求是监控平台侧下发消息有无异常, ...

  5. PostMan 使用Interceptor 发送带cookie的请求一直loading

    问题 最近要写一个爬虫(虽然是第一次写),于是就用了Chrome上非常方便一个插件,PostMan,但是由于chrome安全的限制,发不出带cookie和带有自定义头部标签的请求. 百度一番后得如果想 ...

  6. Postman中使用Postman Interceptor 发送带Cookie 的请求

    使用Postman 发送Cookie 的请求时,发现无法发送成功, 显示"Restricted Header (use Postman Interceptor)" 提示. 网上搜了 ...

  7. 使用Postman Interceptor发送带cookie的请求一直loading的解决法案

    很多web网页开发人员都知道Postman限制由于chrome安全的限制,发不出带cookie和带有自定义头部标签的请求.想要发出由于chrome安全的限制,发不出带cookie和带有自定义头部标签的 ...

  8. .NetCore HttpClient发送请求的时候为什么自动带上了一个RequestId头部?

    奇怪的问题 最近在公司有个系统需要调用第三方的一个webservice.本来调用一个下很简单的事情,使用HttpClient构造一个SOAP请求发送出去拿到XML解析就是了. 可奇怪的是我们的请求在运 ...

  9. RestTemplate发送请求并携带header信息 RestTemplate post json格式带header信息

    原文地址:  http://www.cnblogs.com/hujunzheng/p/6018505.html RestTemplate发送请求并携带header信息   v1.使用restTempl ...

随机推荐

  1. Linux下几种文件传输命令

    Linux下几种文件传输命令 sz rz sftp scp 最近在部署系统时接触了一些文件传输命令,分别做一下简单记录: 1.sftp Secure Ftp 是一个基于SSH安全协议的文件传输管理工具 ...

  2. noip模拟赛 排序

    分析:因为序列是不严格单调的,所以挪动一个数其实就相当于把这个数给删了.如果a[i] < a[i-1],那么可以删掉a[i],也可以删掉a[i-1](!如果没考虑到这一点就只有90分),删后判断 ...

  3. [Bzoj4196] [NOI2015] 软件包管理器 [树链剖分,线段树]

    题解摘要:树链剖分后用线段树区间查询修改,对于安装软件,将改点到根的路径全部变为1,对于卸载软件,将子树清空.注意边界,编号是从0开始的,容易漏掉树根. 第一次写树剖- #include <io ...

  4. PHP array_flip()

    定义和用法 array_flip() 函数返回一个反转后的数组,如果同一值出现了多次,则最后一个键名将作为它的值,所有其他的键名都将丢失. 如果原数组中的值的数据类型不是字符串或整数,函数将报错. 语 ...

  5. 使用resultMap实现ibatis复合数据结构查询(1.多重属性查询;2.属性中含有列表查询)

    以订单为例(订单详情包括了订单的基本信息,配送物流信息,商品信息),直接上代码: 1.多重属性查询 java实体 public class OrderDetail { @XmlElement(requ ...

  6. ICM Technex 2017 and Codeforces Round #400 (Div. 1 + Div. 2, combined) C. Molly's Chemicals

    感觉自己做有关区间的题目方面的思维异常的差...有时简单题都搞半天还完全没思路,,然后别人提示下立马就明白了...=_= 题意:给一个含有n个元素的数组和k,问存在多少个区间的和值为k的次方数. 题解 ...

  7. ytu2572——猜灯谜

    题目描写叙述 A 村的元宵节灯会上有一迷题: 请猜谜 * 请猜谜 = 请边赏灯边猜 小明想,一定是每一个汉字代表一个数字,不同的汉字代表不同的数字. 请你帮小明把全部的可能的数都找出来吧. 输入 没有 ...

  8. luogu1005 矩阵取数游戏

    题目大意 一个矩阵,每次从每一行的行首或行尾取一个数,每一行的价值为 取的数*2^当前取数的次数,每一次的价值为每一行的价值的和.求得到的价值的最大值. 思路 #include <cstdio& ...

  9. Android 系统开机logo的修改【转】

    本文转载自:http://blog.csdn.net/yandongqiangZHRJ/article/details/8585273 看到了好几个修改logo的博文,但是说的不是很清楚,在这里亲手送 ...

  10. mac os lscpu 【转】

    CPU Information on Linux and OS X This is small blog post detailing how to obtain information on you ...