C# 发送带cookie的http请求_C#发送请求带cookie
一、Get请求带cookie
发送带cookie的请求,最好带上浏览器代理字符串:
Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.88 Safari/537.36
/// <summary>
/// get请求,带cookie
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
public static async Task<string> GetAsync(string url, string cookie)
{
HttpClient client = new HttpClient();
if (string.IsNullOrEmpty(cookie) == false)
{
client.DefaultRequestHeaders.Add("cookie", cookie);
}
//指定浏览器代理
client.DefaultRequestHeaders.Add("user-agent", UserAgent);
HttpResponseMessage resp = await client.GetAsync(url);
//获取请求内容
HttpContent respContent = resp.Content;
return await respContent.ReadAsStringAsync();
}
二、Post请求带cookie
/// <summary>
/// Post 请求,无参(注:默认使用UTF8编码)
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
public static async Task<string> PostAsync(string url, string content, string cookie)
{
HttpClient client = new HttpClient();
if (string.IsNullOrEmpty(cookie) == false)
{
client.DefaultRequestHeaders.Add("cookie", cookie);
}
//指定浏览器代理
client.DefaultRequestHeaders.Add("user-agent", UserAgent);
using (MemoryStream ms = new MemoryStream())
{
byte[] bytes = Encoding.UTF8.GetBytes(content);
ms.Write(bytes, 0, bytes.Length);
ms.Seek(0, SeekOrigin.Begin);//设置指针读取位置,否则发送无效
HttpContent hc = new StreamContent(ms);
HttpResponseMessage resp = await client.PostAsync(url, hc);
return await resp.Content.ReadAsStringAsync();
}
}
更多:
C# Post提交formdata类型数据-.Net Core
|