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

半腔热情 提交于 2019-12-21 01:18:17

问题


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, nlauth_email=xxx@xx.com, 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, nlauth_email=xxx@xx.com, nlauth_signature=Pswd1234567, nlauth_role=3","Content-Type":"application/json");

回答1:


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,nlauth_email=xxx@xx.com, nlauth_signature=Pswd1234567, nlauth_role=3";
string contentTypeValue = "application/json";

client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(authValue);
client.DefaultRequestHeaders.Add("Content-Type", contentTypeValue);



回答2:


I know this was asked a while ago, but Juan's solution didn't work for me.

(Also, pretty sure this question is duplicated here.)

The method that finally worked was to use HttpClient with HttpRequestMessage and HttpResponseMessage.

Also note that this is using Json.NET from Newtonsoft.

    using System;
    using System.Net.Http;
    using System.Text;
    using System.Threading.Tasks;
    using System.Net.Http.Headers;
    using Newtonsoft.Json;

    namespace NetsuiteConnector
    {
        class Netsuite
        {

            public void RunHttpTest()
            {
                Task t = new Task(TryConnect);
                t.Start();
                Console.WriteLine("Connecting to NS...");
                Console.ReadLine();
            }

            private static async void TryConnect()
            {
                // dummy payload
                String jsonString = JsonConvert.SerializeObject(
                    new NewObj() {
                        Name = "aname",
                        Email = "someone@somewhere.com"
                    }
                );

                string auth = "NLAuth nlauth_account=123456,nlauth_email=youremail@somewhere.com,nlauth_signature=yourpassword,nlauth_role=3";

                string url  = "https://somerestleturl";
                var uri     = new Uri(@url);

                HttpClient c = new HttpClient();
                    c.BaseAddress = uri;
                    c.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", auth);
                    c.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Post, url);
                req.Content = new StringContent(jsonString, Encoding.UTF8, "application/json");

                HttpResponseMessage httpResponseMessage = await c.SendAsync(req);
                httpResponseMessage.EnsureSuccessStatusCode();
                HttpContent httpContent = httpResponseMessage.Content;
                string responseString = await httpContent.ReadAsStringAsync();

                Console.WriteLine(responseString);
            }
        }

        class NewObj
        {
            public string Name { get; set; }
            public string Email { get; set; }
        }
    }


来源:https://stackoverflow.com/questions/44312426/set-authorization-content-type-headers-when-call-httpclient-postasync

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!