调用HTTPClient.PostAsync时设置标头

时间:2017-06-01 16:08:00

标签: c# netsuite

使用简单的HTTPClient时,我可以将标头设置为REST服务调用吗?

我做:

    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

我不会添加的标题是:

{"Authorization":"NLAuth nlauth_account=5731597_SB1, nlauth_email=xxx@xx.com, nlauth_signature=Pswd1234567, nlauth_role=3","Content-Type":"application/json"}

我应该遵循:

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

3 个答案:

答案 0 :(得分:9)

添加标题的方法如下:

CREATE TABLE dsp$formattedNumber ( 
id INT(11) UNSIGNED NOT NULL AUTO_INCREMENT, 
tanggal DATE NULL, 
tbs_terhadap VARCHAR(100) NULL, 
keterangan VARCHAR(100) NULL, 
masuk VARCHAR(100) NULL, 
keluar VARCHAR(100) NULL, 
saldo_dsp VARCHAR(100) NULL, 
tbs_id INT(11) NOT NULL, 
CONSTRAINT pk_dsp$formattedNumber PRIMARY KEY(id) ) 
DEFAULT CHARACTER SET = utf8 COLLATE = utf8_general_ci;

或者如果你想要一些自定义标题:

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

这个答案已有SO回复,见下文:

更新

似乎你要添加两个标题;授权和内容类型。

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

答案 1 :(得分:1)

我知道这是前一段时间被问过的,但Juan的解决方案对我不起作用。

(另外,非常确定这个问题是重复的here。)

最终工作的方法是将HttpClient与HttpRequestMessageHttpResponseMessage一起使用。

另请注意,这是使用Newtonsoft的Json.NET

    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; }
        }
    }

答案 2 :(得分:1)

如果您使用的是HttpClientFactory,其他答案将不起作用,并here's some reasons为什么使用。使用HttpClientFactory时,可以从池中重用HttpMessages,因此应为每个请求中使用的标头保留默认标头的设置。

如果只想添加内容类型标头,则可以使用备用PostAsJsonAsyncPostAsXmlAsync

var response = await _httpClient.PostAsJsonAsync("account/update", model);

不幸的是,我没有比这更好的添加授权标头的解决方案。

_httpClient.DefaultRequestHeaders.Add(HttpRequestHeader.Authorization.ToString(), $"Bearer {bearer}");