C#首次登录请求后,在后面的所有请求接口中需要带上Cookie,写一个详细完整的HttpHelper请求帮助类
时间: 2024-12-01 10:20:39 浏览: 8
C#模拟Http与Https请求框架类实例
在C#中创建一个带Cookie重用功能的HTTP请求辅助类(假设我们叫它`CookieBasedHttpHelper`),可以按照以下步骤设计:
1. 引入必要的命名空间:
```csharp
using System;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
```
2. 定义一个基础请求类,继承自HttpClient并维护一个 cookie jar:
```csharp
public class CookieBasedHttpClient : HttpClient
{
private readonly CookieContainer _cookieContainer;
public CookieBasedHttpClient()
{
_cookieContainer = new CookieContainer();
}
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
// 先尝试从容器中获取现有Cookie
var cookiesFromJar = await GetCookiesFromContainer(request.RequestUri);
// 如果有Cookie,则添加到请求头
if (cookiesFromJar.Count > 0)
request.Headers.Add(HttpRequestHeader.Cookie, string.Join("; ", cookiesFromJar));
// 发送原始请求
var response = await base.SendAsync(request, cancellationToken);
// 保存新Cookie
foreach (var cookie in response.Cookies)
_cookieContainer.Add(response.RequestMessage.RequestUri, cookie);
return response;
}
private async Task<CookieCollection> GetCookiesFromContainer(Uri uri)
{
try
{
return await _cookieContainer.GetCookiesAsync(uri);
}
catch (Exception ex)
{
Console.WriteLine($"Error retrieving cookies: {ex.Message}");
return null;
}
}
}
```
3. 创建一个封装发送请求的方法,例如`GetUrlResponse`和`GetUrlRespHtml`:
```csharp
public class CookieBasedHttpHelper
{
private readonly CookieBasedHttpClient _client;
public CookieBasedHttpHelper()
{
_client = new CookieBasedHttpClient();
}
public async Task<HttpResponseMessage> getUrlResponse(string url)
{
return await _client.GetAsync(url);
}
public async Task<string> getUrlRespHtml(string url)
{
var response = await getUrlResponse(url);
using (var content = await response.Content.ReadAsStreamAsync())
{
return Encoding.UTF8.GetString(content.ToArray());
}
}
// 设置代理IP的方法(如果需要)
public void SetProxy(string proxyAddress, int port)
{
_client.BaseAddress = new Uri(proxyAddress);
}
}
```
现在你可以使用`CookieBasedHttpHelper`类来发起请求,每次请求都会自动携带上之前的Cookie。示例用法如下:
```csharp
CookieBasedHttpHelper helper = new CookieBasedHttpHelper();
// 第一次登录请求,保存登录产生的Cookie
HttpResponseMessage loginResponse = await helper.getUrlResponse(loginEndpoint);
// 后续接口请求
string homepageContent = await helper.getUrlRespHtml(homepageEndpoint);
```
阅读全文