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");
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.
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.
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:
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With