【问题标题】:HTTP Client Cookie c#HTTP客户端Cookie c#
【发布时间】:2016-04-26 14:02:18
【问题描述】:

我正在尝试设置 cookie 并通过一般方法获取 cookie。我看到了这个有效的示例,但是我在更改自己的代码以保持我的一般功能时遇到了麻烦。

 CookieContainer cookies = new CookieContainer();
HttpClientHandler handler = new HttpClientHandler();
handler.CookieContainer = cookies;

HttpClient client = new HttpClient(handler);
HttpResponseMessage response = client.GetAsync("http://google.com").Result;

Uri uri = new Uri("http://google.com");
IEnumerable<Cookie> responseCookies = cookies.GetCookies(uri).Cast<Cookie>();
foreach (Cookie cookie in responseCookies)
    Console.WriteLine(cookie.Name + ": " + cookie.Value);

Console.ReadLine();

我的代码:

 public static HttpClient CreateClientASMtoken(string tokenVal)
    {


        var httpClient = new HttpClient
        {
            BaseAddress = new Uri(urlASM)
        };
        httpClient.DefaultRequestHeaders.Accept.Clear();
        httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        //httpClient.DefaultRequestHeaders.Accept.Add(new Cookie("token", tokenVal));
        return httpClient;
    }

注释代码是我实现这一目标的尝试之一。我使用的另一种通用方法是:

public static async Task<HttpResponseMessage> PostASM(string path, object content)
    {
        string tokenVal = "d2GpEA5r8pwLRcOPxgaygPooldz2OZ2HUZzZ0YDPAOYCIiH4u5";            
        using (var client = CreateClientASMtoken(tokenVal))
        {
            var json = JsonConvert.SerializeObject(content);
            var serializedContent = new StringContent(json, Encoding.UTF8, "application/json");
            var postResponse = await client.PostAsync(path, serializedContent);

            //string response = await postResponse.Content.ReadAsStringAsync();
            return postResponse;
        }
    }

编辑: 我也试过这个:

但它显示一个错误,并且 url 是好的,token 也是如此。 在此先感谢:)

【问题讨论】:

    标签: c# post cookies header httpclient


    【解决方案1】:

    我找到了一种轻松解决问题的方法。感谢那些做出贡献的人。

    public static async Task<string> GetASM(string path)
        {
            string tokenVal = "d2GpEA5r8pwLRcOPxgaygPooldz2OZ2HUZzZ0YDPAOYCIiH4u5";
            Uri uriASM = new Uri(urlASM);
            var cookieContainer = new CookieContainer();
            using (var handler = new HttpClientHandler() { CookieContainer = cookieContainer })
            using (var client = new HttpClient(handler) { BaseAddress = uriASM })
            {
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                {
                    cookieContainer.Add(uriASM, new Cookie("token", tokenVal));
                    var getResponse = await client.GetAsync(path);
                    return await getResponse.Content.ReadAsStringAsync();
                }
            }
        }
    

    【讨论】:

      【解决方案2】:

      要添加 cookie 更改行:

      //httpClient.DefaultRequestHeaders.Accept.Add(new Cookie("token", tokenVal));
      

      到:

      httpClient.DefaultRequestHeaders.Add("Set-Cookie", "token=test; path=/");
      

      如果您不想要路径部分,请继续删除它。

      如果您希望能够从 HttpResponseMessage 中读取 cookie,您需要自己处理解析。

      这是获取所有 cookie 的一种方法:

              HttpClient client = CreateClientASMtoken("");
              HttpResponseMessage response = client.GetAsync("http://localhost").Result;
      
              IEnumerable<string> rawCookies = response.Headers.GetValues("Set-Cookie");
      

      试一试,您会看到与设置它们时相同的格式。如前所述,您需要自己解析它们或找到一个类来为您执行此操作。

      【讨论】:

      • 嗨@FSDaniel 我已经尝试过你的建议,但没有用,并且请求没问题,因为我已经使用 REST Easy 应用程序进行了测试,它可以工作,我替换为“httpClient.DefaultRequestHeaders.Add( "Cookie","token="+tokenVal);"这是一个错误的请求(如果 cookie 错误,服务器会回复)
      猜你喜欢
      • 2015-01-28
      • 2012-08-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多