C#教程

关注公众号 jb51net

关闭
首页 > 软件编程 > C#教程 > httpclient cookie

C# HttpClient Cookie验证解决方法

作者:

本文将详细介绍C# HttpClient Cookie验证解决方法,需要了解的朋友可以参考下
自实现的cookie 验证,远程取值的例子

以下代码配合HttpClient使用可以实现跨域(cookie的读写)
//验证
复制代码 代码如下:

HttpClient httpClient = new HttpClient(url, null, true);
httpClient.PostingData.Add(key,value);//登录用户名
httpClient.PostingData.Add(key,value);//密码
string str = httpClient.GetString();

----写文件 序列化传回来的cookie
复制代码 代码如下:

CookieCollection cookies = httpClient.Context.Cookies;//保存一个全局的cookie文件
FileStream fileStream = new FileStream("xxx.dat", FileMode.Create);
BinaryFormatter b = new BinaryFormatter();
b.Serialize(fileStream, cookies);
fileStream.Close();

--读文件 反序列化cookies 赋给httpClient的cookies
复制代码 代码如下:

FileStream fileStream = new FileStream("xxx.dat", FileMode.Open, FileAccess.Read, FileShare.Read);
BinaryFormatter b = new BinaryFormatter();
CookieCollection cookies = b.Deserialize(fileStream) as CookieCollection;
HttpClient httpClient = new HttpClient("url");//取值的url
httpClient.Context.Cookies = cookies;
string str = httpClient.GetString();
您可能感兴趣的文章:
阅读全文