Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set Authorization/Content-Type headers when call HTTPClient.PostAsync

Tags:

Where can I set headers to REST service call when using simple HTTPClient?

I do :

HttpClient client = new HttpClient(); var values = new Dictionary<string, string> {     {"id", "111"},     {"amount", "22"} }; var content = new FormUrlEncodedContent(values); var uri = new Uri(@"https://some.ns.restlet.uri");  var response = await client.PostAsync(uri, content); var responseString = await response.Content.ReadAsStringAsync(); 

UPD

Headers I want to add:

{     "Authorization": "NLAuth nlauth_account=5731597_SB1, [email protected], nlauth_signature=Pswd1234567, nlauth_role=3",     "Content-Type": "application/json" } 

Should I do the following?

client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Authorization", "NLAuth nlauth_account=5731597_SB1, [email protected], nlauth_signature=Pswd1234567, nlauth_role=3","Content-Type":"application/json"); 
like image 258
vico Avatar asked Jun 01 '17 16:06

vico


People also ask

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.

What is HttpClient PostAsync?

PostAsync(String, HttpContent) Send a POST request to the specified Uri as an asynchronous operation. PostAsync(Uri, HttpContent) Send a POST request to the specified Uri as an asynchronous operation.


1 Answers

The way to add headers is as follows:

HttpClient client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "Your Oauth token"); 

Or if you want some custom header:

HttpClient client = new HttpClient(); client.DefaultRequestHeaders.Add("HEADERNAME", "HEADERVALUE"); 

This answer has SO responses already, see below:

  • Adding headers when using httpClient.GetAsync
  • Setting Authorization Header of HttpClient

UPDATE

Seems you are adding two headerrs; authorization and content type.

string authValue = "NLAuth nlauth_account=5731597_SB1,[email protected], nlauth_signature=Pswd1234567, nlauth_role=3"; string contentTypeValue = "application/json";  client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(authValue); client.DefaultRequestHeaders.Add("Content-Type", contentTypeValue); 
like image 84
Juan Carlos Martínez Avatar answered Sep 27 '22 17:09

Juan Carlos Martínez