Reputation: 9224
So, this is the code I was using
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();
}
and I want to switch to httpclient, which I've got working, except it doesn't pass the Cookie information. I get the information, but just the anonymous information. Not the information for the user that I'm sending across. Here is what I currently have.
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();
Upvotes: 4
Views: 4161
Reputation: 2465
You'll need to use an HttpClientHandler
, add your cookies to it and then pass it into the HttpClient
's constructor.
An example:
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();
I found a reference to this same behavior here, stating that a header named "Cookie" in DefaultRequestHeaders
is ignored and not sent, but seemingly any other value will work as expected.
Upvotes: 5