Adding Http Headers to HttpClient
Solution 1:
Create a HttpRequestMessage
, set the Method to GET
, set your headers and then use SendAsync
instead of GetAsync
.
var client = new HttpClient();
var request = new HttpRequestMessage() {
RequestUri = new Uri("http://www.someURI.com"),
Method = HttpMethod.Get,
};
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("text/plain"));
var task = client.SendAsync(request)
.ContinueWith((taskwithmsg) =>
{
var response = taskwithmsg.Result;
var jsonTask = response.Content.ReadAsAsync<JsonObject>();
jsonTask.Wait();
var jsonObject = jsonTask.Result;
});
task.Wait();
Solution 2:
When it can be the same header for all requests or you dispose the client after each request you can use the DefaultRequestHeaders.Add
option:
client.DefaultRequestHeaders.Add("apikey","xxxxxxxxx");