C# Httpclient编程

复制代码
今天研究了一天C#如何添加cookie到httpcient里面,从而发请求时,能把cookie作为头部发出,最后发现根本加不进去。
Httpclient的cookie是来自上一个请求的响应,httpclient会自动把上一个请求的响应里面的cookie保存起来,所以当发送几个有关联的request,就必须要用同一个Httpclient
示例:
//第一个请求
            HttpClient client = new HttpClient();
            // 为JSON格式添加一个Accept报头
            //client.DefaultRequestHeaders.Accept.Add(
            //    new MediaTypeWithQualityHeaderValue("application/json"));
            string strDecodeBody = HttpUtility.UrlEncode(strBody);
            HttpContent content = new StringContent(strDecodeBody);
            content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            client.DefaultRequestHeaders.Add("user-agent", "Mozilla/5.0");
            client.DefaultRequestHeaders.Add("Authentication", "123");
            HttpResponseMessage response = null;
            response = client.PostAsync(strIP, content).Result;
            if (response != null)
            {
                if (expectCode == HttpStatusCode.OK)
                {
                    var resultValue = response.Content.ReadAsStringAsync().Result;
                    string strResponse = HttpUtility.UrlDecode(resultValue.ToString());
                    string[] strCookies = (string[])response.Headers.GetValues("Set-Cookie");
                    if(strCookies.Length>0)
                    {
                        strCookie = strCookies[0].Substring(0, strCookies[0].IndexOf(';'));
                    }
                }
            }
 
//第二个请求,在这个请求里,没有设置cookie,由于跟第一个请求使用相同httpclient,所以cookie会自动放入请求头部发给服务器
            string strEncodeBody = HttpUtility.UrlEncode(strBody);
            HttpContent content = new StringContent(strEncodeBody);
            content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            HttpResponseMessage response = null;
            response = client.PostAsync(strIP, content).Result;
            if (response != null)
            {
                if (expectCode == HttpStatusCode.OK)
                {
                    var resultValue = response.Content.ReadAsStringAsync().Result;
                    string strResponse = HttpUtility.UrlDecode(resultValue.ToString());
                    return strResponse;
                }
            }




顶
复制代码

 

posted @   shiningrise  阅读(576)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· .NET10 - 预览版1新功能体验(一)
历史上的今天:
2015-10-04 自动升级程序
// 侧边栏目录 // https://blog-static.cnblogs.com/files/douzujun/marvin.nav.my1502.css
点击右上角即可分享
微信分享提示