HTTP客户端Cookie c#

时间:2016-04-26 14:02:18

标签: c# post cookies header httpclient

我正在尝试设置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;
        }
    }

编辑: 我也试过这个:

enter image description here

但它显示错误,网址正常,令牌也是如此。 在此先感谢:)

2 个答案:

答案 0 :(得分:0)

要添加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");

尝试一下,您将看到它们的格式与设置时相同。如上所述,您需要自己解析它们或找一个类来为您完成此任务。

答案 1 :(得分:0)

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

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();
            }
        }
    }