我有一个应用程序,它正在使用IHostedService从后端cs类调用API。使用基本的API调用("http://httpbin.org/ip"),它可以正常工作并返回正确的值,但是我现在需要调用一个Siemens API,它要求我设置一个Authorization,并在主体中放置"grant_type=client_credentials“。
public async Task<string> GetResult()
{
string data = "";
string baseUrl = "https://<space-name>.mindsphere.io/oauth/token";
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", {ServiceCredentialID: ServiceCredentialSecret});
using (HttpResponseMessage res = await client.GetAsync(baseUrl))
{
using (HttpContent content = res.Content)
{
data = await content.ReadAsStringAsync();
}
}
}我想我已经正确地设置了头文件,但是直到完整的请求格式化后我才能确定。是否有可能将请求的正文设置为"grant_type=client_credentials"?
发布于 2018-09-19 22:48:14
据我从西门子API文档可以看出,他们期望表单数据,所以它应该是这样的:
public async Task<string> GetResult()
{
string data = "";
string baseUrl = "https://<space-name>.mindsphere.io/oauth/token";
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", {ServiceCredentialID: ServiceCredentialSecret});
var formContent = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("grant_type", "client_credentials")
});
using (HttpResponseMessage res = await client.PostAsync(baseUrl, formContent))
{
using (HttpContent content = res.Content)
{
data = await content.ReadAsStringAsync();
}
}
}
}https://stackoverflow.com/questions/52404011
复制相似问题