我想设置cookie并从一般方法获取cookie。我看到这个例子可行,但我在改变我自己的代码时遇到麻烦,因为我可以保留我的一般功能。HTTP客户端Cookie c#
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;
}
}
编辑: 我已经试过这太:
但它显示了一个错误,网址为OK,所以是令牌。 感谢提前:)
嗨@FSDaniel我想你的建议,但不工作,要求是可以的,因为我受够了这种高枕无忧的应用程序进行测试和它的作品我代替“httpClient.DefaultRequestHeaders.Add(”曲奇“ ”标记=“ + tokenVal);”和一个不好的请求(如果cookie错误,服务器会回复它) – Antoine