C# 从httpwebrequest切换到httpclient,我可以';我不知道如何发送我的标题?
这就是我使用的代码C# 从httpwebrequest切换到httpclient,我可以';我不知道如何发送我的标题?,c#,.net,windows-runtime,httpclient,C#,.net,Windows Runtime,Httpclient,这就是我使用的代码 string URL = "http://www.test.com/posts/.json"; var getInfo = (HttpWebRequest)HttpWebRequest.Create(URL);{ getInfo.Headers["Cookie"] = CookieHeader; getInfo.ContentType = "application/x-www-form-urlencoded"; using (Web
string URL = "http://www.test.com/posts/.json";
var getInfo = (HttpWebRequest)HttpWebRequest.Create(URL);{
getInfo.Headers["Cookie"] = CookieHeader;
getInfo.ContentType = "application/x-www-form-urlencoded";
using (WebResponse postStream = await getInfo.GetResponseAsync())
{
StreamReader reader = new StreamReader(postStream.GetResponseStream());
string str = reader.ReadToEnd();
}
我想切换到httpclient,我已经开始工作了,只是它不传递Cookie信息。我得到了信息,但只是匿名信息。不是我发送给用户的信息。这是我目前拥有的
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
client.BaseAddress = new Uri("http://www.test.com/");
client.DefaultRequestHeaders.Add("Cookie", CookieHeader);
HttpResponseMessage response = await client.GetAsync("http://www.test.com" + URL);
string str;
str = await response.Content.ReadAsStringAsync();
您需要使用
HttpClientHandler
,将cookie添加到其中,然后将其传递到HttpClient
的构造函数中
例如:
Uri baseUri = new Uri("http://www.test.com/");
HttpClientHandler clientHandler = new HttpClientHandler();
clientHandler.CookieContainer.Add(baseUri, new Cookie("name", "value"));
HttpClient client = new HttpClient(clientHandler);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.BaseAddress = baseUri;
HttpResponseMessage response = await client.GetAsync("http://www.test.com" + URL);
string str2 = await response.Content.ReadAsStringAsync();
我发现了对相同行为的引用,指出在DefaultRequestHeaders
中名为“Cookie”的头被忽略,并且不会被发送,但似乎任何其他值都会按预期工作