Coder Perfect

HttpClient: Adding Http Headers

Problem

Before I send a request to a web service, I need to add http headers to the HttpClient. How do I accomplish that for a single request (rather than for all future requests on the HttpClient)? This is something I’m not convinced is even doable.

var client = new HttpClient();
var task =
    client.GetAsync("http://www.someURI.com")
    .ContinueWith((taskwithmsg) =>
    {
        var response = taskwithmsg.Result;

        var jsonTask = response.Content.ReadAsAsync<JsonObject>();
        jsonTask.Wait();
        var jsonObject = jsonTask.Result;
    });
task.Wait();

Asked by Ryan Pfister

Solution #1

Create a HttpRequestMessage, set the Method to GET, set your headers, and then use SendAsync rather than 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();

Answered by Darrel Miller

Solution #2

DefaultRequestHeaders can be used when all requests have the same header or when the client is disposed after each request. Option to include:

client.DefaultRequestHeaders.Add("apikey","xxxxxxxxx");      

Answered by Taran

Solution #3

Build a request with the custom header before handing it to httpclient to deliver to the http server to establish custom headers ON A REQUEST. eg:

HttpClient client = HttpClients.custom().build();
HttpUriRequest request = RequestBuilder.get()
  .setUri(someURL)
  .setHeader(HttpHeaders.CONTENT_TYPE, "application/json")
  .build();
client.execute(request);

SET ON HTTPCLIENT is the default header that is sent with every request to the server.

Answered by Zimba

Post is based on https://stackoverflow.com/questions/12022965/adding-http-headers-to-httpclient