C# HttpClient设置cookies的两种办法

一般有两种办法

第一种handler.UseCookies=true(默认为true),默认的会自己带上cookies,例如

var handler = new HttpClientHandler() { UseCookies = true };
var client = new HttpClient(handler);// { BaseAddress = baseAddress };
client.DefaultRequestHeaders.Add("user-agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:57.0) Gecko/20100101 Firefox/57.0");
client.DefaultRequestHeaders.Add("Connection", "Keep-Alive");
client.DefaultRequestHeaders.Add("Keep-Alive", "timeout=600");
var content = new FormUrlEncodedContent(new[]
            {
                new KeyValuePair<string, string>("email", "xxxx"),
                new KeyValuePair<string, string>("password", "xxxx"),
            });
var result = await client.PostAsync("https://www.xxxx.com/cp/login", content);
result.EnsureSuccessStatusCode();

这种情况post请求登陆成功后,重定向到别的页面,也会自动带上cookies。如果把handler.UseCookies设置为false,登陆后重定向的话不会自动带上cookies,则又会跳转到登陆页面。

 

第二种设置 handler.UseCookies = false时,则需要手动给headers上加入cookies.

var handler = new HttpClientHandler() { UseCookies = false};
var client = new HttpClient(handler);// { BaseAddress = baseAddress };
var message = new HttpRequestMessage(HttpMethod.Get, url);
message.Headers.Add("Cookie", "session_id=7258abbd1544b6c530a9f406d3e600239bd788fb");
var result = await client.SendAsync(message);
result.EnsureSuccessStatusCode();

如果使用场景是:抓取需要登陆后才能看到的网页数据,建议使用第一种,不需要设置任何cookies,httpclient会自动把登陆后的cookies放置到后面的请求中。

posted @ 2017-12-13 15:28  小猪39505  阅读(10177)  评论(0编辑  收藏  举报