我想設置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