在 .net 4.5 中尝试使用 HttpClient 使 cookie 脱离响应 [英] Struggling trying to get cookie out of response with HttpClient in .net 4.5
问题描述
我有以下成功运行的代码.我不知道如何从响应中获取 cookie.我的目标是我希望能够在请求中设置 cookie 并从响应中获取 cookie.想法?
I've got the following code that works successfully. I can't figure out how to get the cookie out of the response. My goal is that I want to be able to set cookies in the request and get cookies out of the response. Thoughts?
private async Task<string> Login(string username, string password)
{
try
{
string url = "http://app.agelessemail.com/account/login/";
Uri address = new Uri(url);
var postData = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("username", username),
new KeyValuePair<string, string>("password ", password)
};
HttpContent content = new FormUrlEncodedContent(postData);
var cookieJar = new CookieContainer();
var handler = new HttpClientHandler
{
CookieContainer = cookieJar,
UseCookies = true,
UseDefaultCredentials = false
};
var client = new HttpClient(handler)
{
BaseAddress = address
};
HttpResponseMessage response = await client.PostAsync(url,content);
response.EnsureSuccessStatusCode();
string body = await response.Content.ReadAsStringAsync();
return body;
}
catch (Exception e)
{
return e.ToString();
}
}
这是完整的答案:
HttpResponseMessage response = await client.PostAsync(url,content);
response.EnsureSuccessStatusCode();
Uri uri = new Uri(UrlBase);
var responseCookies = cookieJar.GetCookies(uri);
foreach (Cookie cookie in responseCookies)
{
string cookieName = cookie.Name;
string cookieValue = cookie.Value;
}
推荐答案
要将 cookie 添加到请求,请在请求之前使用 CookieContainer.Add(uri, cookie)
填充 cookie 容器.发出请求后,cookie 容器将自动填充响应中的所有 cookie.然后您可以调用 GetCookies() 来检索它们.
To add cookies to a request, populate the cookie container before the request with CookieContainer.Add(uri, cookie)
. After the request is made the cookie container will automatically be populated with all the cookies from the response. You can then call GetCookies() to retreive them.
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();
这篇关于在 .net 4.5 中尝试使用 HttpClient 使 cookie 脱离响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!