首页 > 编程 > C# > 正文

C# HttpClient Cookie验证解决方法

2020-01-24 03:38:35
字体:
来源:转载
供稿:网友
自实现的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();
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表