c# - c# 将 CookieContainer 添加到 HttpClientHandler
问题描述
我有以下用 c# 编写的函数:
public static string FunctionName()
{
try
{
using (var httpClient = new HttpClient())
{
var uri = new Uri("https://www.website.com/api/1/auth/user");
httpClient.BaseAddress = uri;
httpClient.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36");
httpClient.DefaultRequestHeaders.Add("Cookie", "apiKey=dasdasd; auth=authcookie_dasd-c28673189043; id_chat.com=dasdasdad");
return httpClient.GetAsync(uri).Result.ToString();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}
return null;
}
其中 cookie 直接添加到标题中。现在我试图将其拆分以将其添加到 CookieContainer 中。源代码如下所示:
public static string FunctionName()
{
try
{
HttpClientHandler handler = new HttpClientHandler();
handler.CookieContainer = new CookieContainer();
Uri target = new Uri("https://www.website.com");
handler.CookieContainer.Add(new Cookie("apiKey", "dasdasd") { Domain = target.Host });
handler.CookieContainer.Add(new Cookie("auth", "authcookie_dasd-c28673189043") { Domain = target.Host });
handler.CookieContainer.Add(new Cookie("id_chat.com", "dasdasdad") { Domain = target.Host });
HttpClient http = new HttpClient(handler);
http.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36");
var response = http.GetAsync("https://www.website.com/api/1/auth/user");
Console.WriteLine(response.Result.ToString());
if (response.Result.StatusCode == HttpStatusCode.OK)
{
var json = JsonConvert.DeserializeObject<LoginResponse>(response.Result.Content.ReadAsStringAsync().Result);
return json.id;
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}
return null;
}
第一个函数将返回状态“OK”。第二个函数将返回状态“未授权”。
是什么导致了这个问题?我是否设置了 CookieContainer 错误?
解决方案
推荐阅读
- django - 从用户那里获取数据
- python - Python Pandas:如果 Else & .rank() 应用于数据帧
- node.js - 链码的实例化尝试在 /usr/local/src/chaincode.js 中找到链码
- ios - 如何修复没有这样的文件 - ios/platform_www/cordova.js
- javascript - 从 ArcGIS Online 中的 KML 图层获取范围
- python-3.x - 如何在 Python 中修复“找到一个数字的质因数”
- jquery - 如何选择一系列具有不同数字的 div 类?
- c# - 服务未通过 WebClient 接收 API 数据
- firebase - Firestore 安全规则 email_verified 不起作用
- javascript - 在 xhttp 删除请求上未定义节点 req.body