C# 发送带cookie的http请求_C#发送请求带cookie

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

/// 
/// get请求,带cookie
/// 
/// 
/// 
public static async Task 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

/// 
/// Post 请求,无参(注:默认使用UTF8编码)
/// 
/// 
/// 
public static async Task 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

C# 正则表达式使用_C# Regex使用整理

C# 正则使用_正则表达式使用整理(一)

你可能感兴趣的:(C#网络编程,C#,发送带http请求,C#发送请求带cookie)