4

所以,这是我使用的代码



    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();

4

1 回答 1

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();

我在这里找到了对相同行为的引用,指出名为“Cookie”的标头DefaultRequestHeaders被忽略且未发送,但似乎任何其他值都会按预期工作。

于 2012-12-09T07:16:53.063 回答