gpt4 book ai didi

c# - HTTP 客户端 Cookie c#

转载 作者:太空宇宙 更新时间:2023-11-03 15:22:05 26 4
gpt4 key购买 nike

我正在尝试通过通用方法设置 cookie 和获取 cookie。

我看到了这个有效的示例,但我在更改我自己的代码以保持我的一般功能的方式时遇到了麻烦。

CookieContainer cookies = new CookieContainer();
HttpClientHandler handler = new HttpClientHandler();
handler.CookieContainer = cookies;

HttpClient client = new HttpClient(handler);
HttpResponseMessage response = client.GetAsync("http://google.com").Result;

Uri uri = new Uri("http://google.com");
IEnumerable<Cookie> responseCookies = cookies.GetCookies(uri).Cast<Cookie>();
foreach (Cookie cookie in responseCookies)
Console.WriteLine(cookie.Name + ": " + cookie.Value);

Console.ReadLine();

我的代码:

public static HttpClient CreateClientASMtoken(string tokenVal)
{
var httpClient = new HttpClient
{
BaseAddress = new Uri(urlASM)
};
httpClient.DefaultRequestHeaders.Accept.Clear();
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
//httpClient.DefaultRequestHeaders.Accept.Add(new Cookie("token", tokenVal));
return httpClient;
}

注释代码是我为实现这一目标所做的尝试之一。我使用的另一种通用方法是:

public static async Task<HttpResponseMessage> PostASM(string path, object content)
{
string tokenVal = "d2GpEA5r8pwLRcOPxgaygPooldz2OZ2HUZzZ0YDPAOYCIiH4u5";
using (var client = CreateClientASMtoken(tokenVal))
{
var json = JsonConvert.SerializeObject(content);
var serializedContent = new StringContent(json, Encoding.UTF8, "application/json");
var postResponse = await client.PostAsync(path, serializedContent);

//string response = await postResponse.Content.ReadAsStringAsync();
return postResponse;
}
}

编辑:我也试过这个:

enter image description here

但它显示错误,URL 和 token 都没有问题。

最佳答案

我找到了一种轻松解决问题的方法。感谢做出贡献的人。

public static async Task<string> GetASM(string path)
{
string tokenVal = "d2GpEA5r8p...";
Uri uriASM = new(urlASM);
var cookieContainer = new CookieContainer();

using var handler = new HttpClientHandler()
{
CookieContainer = cookieContainer,
};

using var client = new HttpClient(handler)
{
BaseAddress = uriASM,
};

client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));

cookieContainer.Add(uriASM, new Cookie("token", tokenVal));
var getResponse = await client.GetAsync(path);
return await getResponse.Content.ReadAsStringAsync();
}

关于c# - HTTP 客户端 Cookie c#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36867242/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com