简体   繁体   中英

How to call Rest API with Content and Headers in c#?

I am trying to call Rest API with content and headers in c#. Actually I am trying to convert to c# from Python code which is:

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)

So far I am trying with:

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

I have no idea how to put from Python code Headers (Content-Type) and additional string (payload).

If you use RestSharp , you should be able to call your service with the following code snipped

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;

I based my answer on the anwser of this answer .

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

Or use FormUrlEncodedContent without set header

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

If you write UWP application, use HttpStringContent or HttpFormUrlEncodedContent instead in Windows.Web.Http.dll.

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

Here a sample I use in one of my apps:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM