#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. hdu_2046_骨牌铺方格_201311251403

    骨牌铺方格 Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others) Total Subm ...

  2. POJ2777 Count Color 线段树区间更新

    题目描写叙述: 长度为L个单位的画板,有T种不同的颜料.现要求按序做O个操作,操作分两种: 1."C A B C",即将A到B之间的区域涂上颜色C 2."P A B&qu ...

  3. 从头认识Spring-2.7 自己主动检測Bean(1)-@Component @Repository @Service @Controller

    这一章节我们来讨论一下自己主动检測Bean. 1.domain 厨师类: package com.raylee.my_new_spring.my_new_spring.ch02.topic_1_19; ...

  4. Android - Error: &quot;java.io.IOException: setDataSource failed.: status=0x80000000&quot;

    Error: "java.io.IOException: setDataSource failed.: status=0x80000000" 本文地址: http://blog.c ...

  5. mongoDB学习笔记——存取图片(C#)

    作为一个NoSql数据库的代表,存取多媒体数据,应该是强项吧?那么,图片在mongoDB里是如何存取的呢?(其实,关系型数据库存取图片也一点问题没有,所以我看NoSql的强项不在于是否存储多媒体,而在 ...

  6. luogu3469 [POI2008]BLO_Blockade

    题目大意 给一个无向连通图,求对于每一个点,去掉该点后图中连通结点有序对的减少量. 思路 当时想这道题时,我想到:枚举每一个点,在删去它后连通的几个部分中Dfs得到各个部分的点的个数从而得到解,但是我 ...

  7. 使用poi读取word2007(.docx)中的复杂表格

    使用poi读取word2007(.docx)中的复杂表格 最近工作需要做一个读取word(.docx)中的表格,并以html形式输出.经过上网查询,使用了poi. 对于2007及之后的word文档,需 ...

  8. Socket之shutdown()用法

    通常来说,socket是双向的,即数据是双向通信的.但有些时候,你会想在socket上实现单向的socket,即数据往一个方向传输. 单向的socket便称为半开放Socket.要实现半开放式,需要用 ...

  9. nyoj--1100--WAJUEJI which home strong!(bfs)

    WAJUEJI which home strong! 时间限制:1000 ms  |  内存限制:65535 KB 难度:2 描述 在一个山沟里,姐弟俩同时考上了大学.但由于家里拮据,所以这并不是什么 ...

  10. hdu1704——floyd

    Problem Description there are N ACMers in HDU team.ZJPCPC Sunny Cup 2007 is coming, and lcy want to ...