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 == )
{
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发送请求的更多相关文章
- python的requests库怎么发送带cookies的请求
背景: 在用robot做接口自动化时,有一个查询接口需要用到登录后返回的token等信息作为cookies作为参数一起请求(token是在返回体中,并不在cookies中), 刚好create se ...
- 测试框架httpclent 3.获取cookie的信息,然后带cookies去发送请求
在properties文件里面: startupWithCookies.json [ { "description":"这是一个会返回cookies信息的get请求&qu ...
- Python接口测试实战2 - 使用Python发送请求
如有任何学习问题,可以添加作者微信:lockingfree 课程目录 Python接口测试实战1(上)- 接口测试理论 Python接口测试实战1(下)- 接口测试工具的使用 Python接口测试实战 ...
- Requests发送带cookies请求
一.缘 起 最近学习[悠悠课堂]的接口自动化教程,文中提到Requests发送带cookies请求的方法,笔者随之也将其用于手头实际项目中,大致如下 二.背 景 实际需求是监控平台侧下发消息有无异常, ...
- PostMan 使用Interceptor 发送带cookie的请求一直loading
问题 最近要写一个爬虫(虽然是第一次写),于是就用了Chrome上非常方便一个插件,PostMan,但是由于chrome安全的限制,发不出带cookie和带有自定义头部标签的请求. 百度一番后得如果想 ...
- Postman中使用Postman Interceptor 发送带Cookie 的请求
使用Postman 发送Cookie 的请求时,发现无法发送成功, 显示"Restricted Header (use Postman Interceptor)" 提示. 网上搜了 ...
- 使用Postman Interceptor发送带cookie的请求一直loading的解决法案
很多web网页开发人员都知道Postman限制由于chrome安全的限制,发不出带cookie和带有自定义头部标签的请求.想要发出由于chrome安全的限制,发不出带cookie和带有自定义头部标签的 ...
- .NetCore HttpClient发送请求的时候为什么自动带上了一个RequestId头部?
奇怪的问题 最近在公司有个系统需要调用第三方的一个webservice.本来调用一个下很简单的事情,使用HttpClient构造一个SOAP请求发送出去拿到XML解析就是了. 可奇怪的是我们的请求在运 ...
- RestTemplate发送请求并携带header信息 RestTemplate post json格式带header信息
原文地址: http://www.cnblogs.com/hujunzheng/p/6018505.html RestTemplate发送请求并携带header信息 v1.使用restTempl ...
随机推荐
- 洛谷—— P1092 虫食算
https://www.luogu.org/problem/show?pid=1092 题目描述 所谓虫食算,就是原先的算式中有一部分被虫子啃掉了,需要我们根据剩下的数字来判定被啃掉的字母.来看一个简 ...
- 51Nod——T 1109 01组成的N的倍数
https://www.51nod.com/onlineJudge/questionCode.html#!problemId=1109 基准时间限制:1 秒 空间限制:131072 KB 分值: 40 ...
- php svn仓库提交预处理
需要做的事情 1.检查是否填写注释2.php文件是否有语法错误 pre-commit脚本 hook脚本名称:hooks/pre-commit REPOS="$1" TXN=&quo ...
- 源代码:windows文件切割与合并
#include <Windows.h> #include <vector> #include <string> using namespace std; //推断 ...
- IOS_OC_Category
1.Category概述 那的Category的使用场景有那些呢: 1.类包括了非常多个方法实现,而这些方法须要不同团队的成员来实现 2.当你在使用基础类库中的类时,你不想继承这些类而仅仅想加入一些方 ...
- Axure RP一个专业的高速原型设计工具
Axure RP是一个专业的高速原型设计工具.Axure(发音:Ack-sure),代表美国Axure公司.RP则是Rapid Prototyping(高速原型)的缩写. Axure简要介绍 Axur ...
- pascal+sublime搭建Pascal学习环境
一.fpc安装 1. 下载:http://www.freepascal.org/down/i386/win32.var(或者:http://download.csdn.net/detail/wenph ...
- webService总结(一)——使用CXF公布和调用webService(不使用Spring)
CXF和Axis2是两个比較流行的webService框架,接下来我会写几篇博客简介怎样使用这两种框架. 首先,先简介一下CXF的使用. CXF公布webService有多种方法.这里我介绍三种: 1 ...
- luogu1070 道路游戏 单调队列
题目大意 小新正在玩一个简单的电脑游戏. 游戏中有一条环形马路,马路上有 nn 个机器人工厂,两个相邻机器人工厂之间由一小段马路连接.小新以某个机器人工厂为起点,按顺时针顺序依次将这 nn 个机器人工 ...
- 海思3518e mpp2/sample/venc makefile简析
http://blog.csdn.net/u011003120/article/details/51324567