【发布时间】:2016-04-26 14:02:18
【问题描述】:
我正在尝试设置 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;
}
}
编辑: 我也试过这个:
但它显示一个错误,并且 url 是好的,token 也是如此。 在此先感谢:)
【问题讨论】:
标签: c# post cookies header httpclient