从httpwebrequest切换到httpclient,我无法弄清楚如何发送我的标题?

时间:2012-12-09 05:18:19

标签: 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 (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();

1 个答案:

答案 0 :(得分:5)

您需要使用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();

我找到了对同一行为here的引用,声明DefaultRequestHeaders中名为“Cookie”的标头被忽略而未发送,但看似任何其他值都会按预期工作。