C# HttpClient设置cookies的两种办法

2021-07-25 20:54

阅读:846

一般有两种办法

第一种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 KeyValuePairstring, string>("email", "xxxx"),
                new KeyValuePairstring, 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();

 


评论


亲,登录后才可以留言!