【问题标题】:How to call Rest API with Content and Headers in c#?如何在 C# 中使用 Content 和 Headers 调用 Rest API?
【发布时间】:2019-03-24 14:20:45
【问题描述】:

我正在尝试使用 c# 中的内容和标头调用 Rest API。实际上我正在尝试从 Python 代码转换为 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;
}

我不知道如何从 Python 代码中放入 Headers (Content-Type) 和附加字符串 (payload)。

【问题讨论】:

  • 我根据HttpClient给了你一个答案。请检查。

标签: c# rest


【解决方案1】:

这是我在我的一个应用中使用的示例:

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

【讨论】:

  • 是的,像这样,你是如何解决像 timeout=undefined 和 allow_redirects=False 这样的设置的
  • @DaniKR 像这样:_client = new HttpClient { BaseAddress = new Uri(ConfigManager.Api.BaseUrl), Timeout = new TimeSpan(0, 0, 0, 0, -1) };跨度>
  • 只要指定你想要的超时时间
【解决方案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 的答案。

【讨论】:

    【解决方案3】:
    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);
    

    【讨论】:

    • 我必须为“HttpFormUrlEncodeContent”使用什么参考?
    • Windows.Web.Http.dll。我还为普通的 .net api 添加了代码。
    • 你让它看起来好像你不能同时指定你的数据和标题。这是不正确的。
    猜你喜欢
    • 2012-03-26
    • 1970-01-01
    • 2021-12-24
    • 1970-01-01
    • 1970-01-01
    • 2023-03-07
    • 1970-01-01
    相关资源
    最近更新 更多