挣扎试图让Cookie不符合.net 4.5中的HttpClient的响应
我有下面的代码,成功的工作。 我无法弄清楚如何从响应中获取cookie。 我的目标是,我希望能够在请求中设置cookie,并将cookie从响应中取出。 思考?
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()来检索它们。
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();