All:

I need to add http headers to the HttpClient before I send a request to a web service. How do I do that for an individual request (as opposed to on the HttpClient to all future requests)? I'm not sure if this is even possible.

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

Thanks in advance for any help you provide.

share|improve this question

2 Answers

up vote 7 down vote accepted

Create a HTTPResponseMEssage, 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();
}
share|improve this answer
Just what I needed. Thanks! – Ryan Pfister Aug 19 '12 at 17:41
Thanks, Darrel! I was disappointed with HttpClient until I saw that you could do this. – Sam Feb 22 at 22:05

If you use RestSharp you can easily add them to the request (there is an example on the front page).

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.