zoukankan      html  css  js  c++  java
  • 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;
                    }
                }
    
    
    
    
    顶
  • 相关阅读:
    训练计划
    LA_3942 LA_4670 从字典树到AC自动机
    HDU 6180 Schedule
    HDU 6153 KMP
    HDU 2087 HDU 1867 KMP标准模板题
    Struts2学习8--文件上传(单个文件上传)
    SSH错误之--Error getting property descriptor: null at com.opensymphony.xwork2.ognl.accessor.XWorkCollectionPropertyAccessor.getProperty
    Struts2学习7---集合类型的类型转换
    工具-windows命令--查看端口占用情况,关闭端口
    Struts2学习6—OGNL (1)
  • 原文地址:https://www.cnblogs.com/shiningrise/p/5931362.html
Copyright © 2011-2022 走看看