调用HTTPClient.PostAsync时设置Authorization/Content-Type标头 [英] Set Authorization/Content-Type headers when call HTTPClient.PostAsync
本文介绍了调用HTTPClient.PostAsync时设置Authorization/Content-Type标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用简单的HTTPClient时,在哪里可以将标头设置为REST服务调用?
Where can I set headers to REST service call when using simple HTTPClient?
我愿意:
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"
}
我应该执行以下操作吗?
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");
推荐答案
添加标头的方法如下:
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");
此答案已经有SO响应,请参见下文:
This answer has SO responses already, see below:
- Adding headers when using httpClient.GetAsync
- Setting Authorization Header of HttpClient
更新
似乎您要添加两个标题.授权和内容类型.
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);
这篇关于调用HTTPClient.PostAsync时设置Authorization/Content-Type标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文