【问题标题】:Submitting a POST with headers and parameters提交带有标题和参数的 POST
【发布时间】:2016-08-16 00:21:19
【问题描述】:

我需要连接到 API,但他们提供的所有连接示例都使用 CURL。我需要在 C# 中实现它。我已将范围缩小到需要使用 httpclient 类,但我似乎找不到任何示例或教程来准确解释我需要什么。这是他们说要使用的 CURL 查询。谁能指出如何将其转换为 c# 的正确方向?

curl -X POST --header 'Content-Type: application/json' --header 'Accept: application/json' --header '授权: Bearer XXXXXXXXXXXXXXXXXXXXXXXXX' -d '{ "grant_type": "密码", “client_id”:XXXX, "用户名": "XXX.XXXXXX@XXXXXXXXX.com", “密码”:“XXXXXXXXXXXXX|XXXXXXXXXXXXX” }' 'https://XXXXXXXXXXXX/XXXXXXXX/XXXXX/XXXXXX/authorize'

提前致谢:)

【问题讨论】:

    标签: c# api curl


    【解决方案1】:

    你可以使用HttpClient类如下

     using (var client = new HttpClient())
                {
    
                    client.BaseAddress = new Uri("http://yourdomain.com");
                    client.DefaultRequestHeaders.Accept.Clear();
    
                    //this line is optional in case you are using basic authentication
                    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
                                                            "Basic",
                                                            Convert.ToBase64String(
                                                                System.Text.ASCIIEncoding.ASCII.GetBytes(
                                                                   string.Format("{0}:{1}", "username", "password"))));
    
                    var content = new FormUrlEncodedContent(new[] 
                                {
                                    new KeyValuePair<string, string>("", "login")
                                });
                    HttpResponseMessage response = client.PostAsync("http//yourdomain.com", content).Result;
                    if (response.IsSuccessStatusCode)
                    {
                        var _result = response.Content.ContentToString();
    
                    }
                }
    

    【讨论】:

      猜你喜欢
      • 2015-10-06
      • 2017-09-30
      • 1970-01-01
      • 2019-01-19
      • 2019-05-13
      • 2018-12-09
      • 2019-09-17
      • 2011-06-14
      • 2014-09-01
      相关资源
      最近更新 更多