Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpClient Headers vs HttpRequestMessage Headers

When should we use headers in the HttpRequestMessage object over headers in the HttpClient ??

We have need to add Authorization (always changing) and few custom headers (always changing )

Questions

  1. Which is the preferred method ?
  2. Should i be adding common headers (same across all the requests) to the HttpClient and request based headers to the HttpRequestMessage object ??

       //HttpRequestMessage Code
        HttpRequestMessage reqmsg =new HttpRequestMessage();
        reqmsg.Headers.Authorization =new AuthenticationHeaderValue("some scheme");
        reqmsg.Headers.Add("name","value");
    
        //HttpClient Code
        HttpClient client =new HttpClient();
        client.DefaultRequestHeaders.Authorization =new AuthenticationHeaderValue("some scheme");
        client.DefaultRequestHeaders.Add("name", "value");
    
like image 817
nen Avatar asked Oct 03 '15 13:10

nen


People also ask

How do you pass headers for HTTP client?

The next step is to send the document to HTTP Server. This can be done by establishing HTTP Session with HTTP Client Begin Session Service, then sending the document using HTTP Client Method Service using GET Method. In order to send HTTP headers with Primary Document, you have to set RawRequest parameter to true.

What are Default request headers?

The DefaultRequestHeaders property represents the headers that an app developer can set, not all of the headers that may eventually be sent with the request. The HttpBaseProtocolFilter will add some additional headers.

What is client DefaultRequestHeaders accept clear ()?

It clears the default headers that are sent with every request. These headers are things that are common to all your requests, e.g. Content-Type, Authorization, etc.


1 Answers

  1. Which is the preferred method ? Should i be adding common headers (same across all the requests) to the HttpClient
  2. and request based headers to the HttpRequestMessage object ??

Your questions are auto-answered themselves.

DefaultRequestHeaders are ones that will be part of any request, which is a plus because you'll be able to avoid repeating yourself adding some headers one over again. In the other hand, HttpRequestMessage.Headers will be only part of that request.

When should you use one over the other? I'm going to use two examples:

  • I need to send an OAuth bearer token as part of every request so I set the Authorization header in the HttpClient.DefaultRequestHeaders, and if I need to refresh the token, I just need to set it again there.

  • I need to send an entity serialized as JSON or XML depending on some condition. That is, I'll set the Content-type header in a per-request basis.

like image 121
Matías Fidemraizer Avatar answered Sep 22 '22 12:09

Matías Fidemraizer