C#用HttpClient类post get,怎么设置cookies
2016-04-05 · 知道合伙人数码行家
huanglenzhi
知道合伙人数码行家
向TA提问 私信TA
知道合伙人数码行家
采纳数:117538
获赞数:517195
长期从事计算机组装,维护,网络组建及管理。对计算机硬件、操作系统安装、典型网络设备具有详细认知。
向TA提问 私信TA
关注
展开全部
自实现的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();
以下代码配合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();
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询