HttpClient传递Cookie
使用代码访问http资源,我们通常用WebRequest,当然,HttpClient提供了更方便的封装,我用得更多。只是碰到一些需要(cookie)鉴权的情况,需要把cookie伴随请求一起发到服务器,如下:
var m = new HttpClient(); var url = new Uri("http://localhost:4567/test"); var cookie = "mycookie=valueofcookie; expires=Thu, 14-Nov-2013 07:21:28 GMT; path=/; HttpOnly";
1,使用WebRequest,完全没问题:
var req = (HttpWebRequest)WebRequest.Create(url); req.Method = "POST"; req.ContentLength = 0; req.Headers.Add("Cookie", cookie); var res = (HttpWebResponse)req.GetResponse(); using (var stream = res.GetResponseStream()) { if (stream != null) Console.WriteLine(new StreamReader(stream, System.Text.Encoding.UTF8).ReadToEnd()); }
2,如果要用HttpClient的话呢?我失败了两次:
我想这么写(2.1):
m.DefaultRequestHeaders.Add("Cookie", cookie); var t = await m.PostAsync(url, null); var c = await t.Content.ReadAsStringAsync(); Console.WriteLine(c);
失败,于是这么写(2.2)
var req = new HttpRequestMessage(HttpMethod.Post, url); req.Headers.Add("Cookie", cookie); var t = await m.SendAsync(req); var c = await t.Content.ReadAsStringAsync(); Console.WriteLine(c);
仍然失败,查到这篇文章,有结论了,使用CookieContainer
var baseAddress = new Uri("http://example.com"); var cookieContainer = new CookieContainer(); using (var handler = new HttpClientHandler() { CookieContainer = cookieContainer }) using (var client = new HttpClient(handler) { BaseAddress = baseAddress }) { //此处是顺便演示如何传Post参数 var content = new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("foo", "bar"), new KeyValuePair<string, string>("baz", "bazinga"), }); cookieContainer.Add(baseAddress, new Cookie("CookieName", "cookie_value")); var result = client.PostAsync("/test", content).Result; result.EnsureSuccessStatusCode(); }
此时有人提出,其实2.2的写法是可以的,之所以cookie没有传递到过去,是因为HttpClientHandler默认用了CookieContainer,所以会忽略掉Header里面的Cookie设置,因此你要做的就是把CookieContainer从HttpClientHandler里禁掉,测试通过:
var m = new HttpClient(new HttpClientHandler { UseCookies = false });
此时方法2.2一个字不要动,cookie顺利传递