如何在C#中使用内容和标题调用Rest API?

时间:2019-03-24 14:20:45

标签: c# rest

我试图用C#中的内容和标头调用Rest Api。实际上,我正在尝试从Pyhton代码转换为c#:

import requests
url = 'http://url.../token'
payload = 'grant_type=password&username=username&password=password'
headers = {
  'Content-Type': 'application/x-www-form-urlencoded'
}
response = requests.request('POST', url, headers = headers, data = payload, allow_redirects=False)
print(response.text)

到目前为止,我正在尝试:

HttpClient client = new HttpClient();
client.BaseAddress = new Uri(Url);

var tmp = new HttpRequestMessage
{
    Method = HttpMethod.Post,
    Content =
            {

            }
     };

    var result = client.PostAsync(Url, tmp.Content).Result;
}

我不知道如何从Pyhton代码标头(内容类型)和additioanl字符串(有效负载)中输入

3 个答案:

答案 0 :(得分:2)

如果您使用RestSharp,则应该可以通过以下代码来调用服务

var client = new RestClient("http://url.../token");
var request = new RestRequest(Method.POST);
request.AddHeader("content-type", "application/x-www-form-urlencoded");
request.AddParameter("application/x-www-form-urlencoded", "grant_type=password&username=username&password=password", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
var result = response.Content;

我的答案基于this answer的答案。

答案 1 :(得分:2)

using System.Net.Http;

var content = new StringContent("grant_type=password&username=username&password=password");
content.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
client.PostAsync(Url, content);

或者使用FormUrlEncodedContent而不设置标头

var data = new Dictionary<string, string>
{
    {"grant_type", "password"},
    {"username", "username"},
    {"password", "password"}
};
var content = new FormUrlEncodedContent(data);
client.PostAsync(Url, content);

如果编写UWP应用程序,请在Windows.Web.Http.dll中使用HttpStringContentHttpFormUrlEncodedContent

using Windows.Web.Http;

var content = new HttpStringContent("grant_type=password&username=username&password=password");
content.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
client.PostAsync(Url, content);

var data = new Dictionary<string, string>
{
    {"grant_type", "password"},
    {"username", "username"},
    {"password", "password"}
};
var content = new FormUrlEncodedContent(data);
client.PostAsync(Url, content);

答案 2 :(得分:2)

以下是我在其中一个应用中使用的示例:

_client = new HttpClient { BaseAddress = new Uri(ConfigManager.Api.BaseUrl), Timeout = new TimeSpan(0, 0, 0, 0, -1) };

      _client.DefaultRequestHeaders.Accept.Clear();
      _client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
_client.DefaultRequestHeaders.Add("Bearer", "some token goes here");
相关问题