代码之家  ›  专栏  ›  技术社区  ›  DaniKR Saranga

如何用c_中的内容和头调用rest api?

  •  0
  • DaniKR Saranga  · 技术社区  · 6 年前

    我试图用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代码头(内容类型)和附加字符串(有效负载)中放置。

    2 回复  |  直到 6 年前
        1
  •  2
  •   Jonathan Alfaro    6 年前

    以下是我在某个应用程序中使用的示例:

    _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");
    
        2
  •  2
  •   Volkmar Rigo    6 年前

    如果你使用 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
  •  2
  •   shingo    6 年前
    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应用程序,请使用 HttpStringContent HttpFormUrlEncodedContent 而是在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=新字典<字符串,字符串>
    {
    {“授权类型”,“密码”},
    {“用户名”,“用户名”},
    {“密码”,“密码”}
    };
    var content=new formurlencodedcontent(数据);
    client.postsync(url,内容);