#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. Awesome Python(中文对照)

    python中文资源大全:https://github.com/jobbole/awesome-python-cn A curated list of awesome Python framework ...

  2. Leetcode 30.与所有单词相关联的子串

    与所有单词相关联的字串 给定一个字符串 s 和一些长度相同的单词 words.在 s 中找出可以恰好串联 words 中所有单词的子串的起始位置. 注意子串要与 words 中的单词完全匹配,中间不能 ...

  3. Codeforces Round #418 (Div. 2) C. An impassioned circulation of affection

    C. An impassioned circulation of affection time limit per test 2 seconds memory limit per test 256 m ...

  4. What you can talk

    data buffer who locked the account hash join cost memory and nested loop do not. How to make it hash ...

  5. Androd自己定义控件(三)飞翔的小火箭

    在前面的自己定义控件概述中已经跟大家分享了Android开发其中自己定义控件的种类. 今天跟大家分享一个非主流的组合控件. 我们在开发其中,难免须要在不同的场合中反复使用一些控件的组合.而Java的最 ...

  6. UML类图符号解释

    在UML类图中,常见的有以下几种关系:  泛化(Generalization)和  实现(Realization) - 父子关系 依赖(Dependency) - 局部变量.方法參数 聚合(Aggre ...

  7. SpringMVC高速实现文件上传功能

    SpringMVC为我们封装了上传文件的功能,如今就试用一下 须要的jar包 我用的是Maven项目,就不须要到处下载Jar包了 SpringMVC的搭建 首先要在applicationContext ...

  8. Bean Query 改动Bug的版本号(1.0.1)已公布

    改动内容: 修复输入对象被排序的属性不存在或者为Null时出错的bug 在Maven项目中引用 <dependency> <groupId>cn.jimmyshi</gr ...

  9. c# 删除程序占用的文件,强力删除文件,彻底删除文件,解除文件占用

    c# 删除程序占用的文件.清理删除文件.彻底删除文件,解除文件占用 文件打开时,以共享读写模式打开 FileStream inputStream = new FileStream(name, File ...

  10. 编程算法 - 和为s的连续正整数序列 代码(C)

    和为s的连续正整数序列 代码(C) 本文地址: http://blog.csdn.net/caroline_wendy 题目: 输入一个正数s, 打印出全部和为s的连续正数序列(至少含有两个数). 起 ...