【问题标题】:How to call third party Restful API [closed]如何调用第三方 Restful API [关闭]
【发布时间】:2018-01-10 17:03:49
【问题描述】:

我们如何在 C# webClient 中调用以下端点,我已经使用 GoogleScript 进行了管理,但现在我需要在 C# 中使用它

      var options = {
    "async": true,
    "crossDomain": true,
    "method" : "GET",
    "headers" : {
      "X-Api-Key" : "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
      "X-Api-Secret": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
    }
  };

  var response = UrlFetchApp.fetch('https://dashboard.reviewpush.com/api/company/locations',options);
  var pages = JSON.parse(response.getContentText());

我们如何将具有多个值的标头传递给请求,我尝试过的代码如下

public static void Main (string[] args)
{
    string url = "https://dashboard.reviewpush.com/api/company/locations";

    using (var client = new WebClient())
    {
        client.Headers[HttpRequestHeader.ContentType] = "application/json";
        client.Headers["X-IFORM-API-REQUEST-ENCODING"] = "JSON";
        client.Headers["async"] ="true";
        client.Headers["crossDomain"] = "true";
        client.Headers["method"] = "GET";
        client.Headers["headers"] = "{'X-Api-Key' : 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
          'X-Api-Secret': 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
}";

        Stream data = client.OpenRead (args[0]);
        StreamReader reader = new StreamReader (data);
        string s = reader.ReadToEnd ();
        Console.WriteLine (s);
        data.Close();
        reader.Close();
}

【问题讨论】:

  • 我想在这里回答stackoverflow.com/questions/47948266/…会对你有所帮助
  • 那么,您尝试了什么?你希望我们做你的工作吗?
  • 你有 RTFM 了吗? msdn.microsoft.com/en-us/library/… -- 页面上有一个示例,您可以将其用作起点。
  • @RICKYKUMAR 这是一个使用旧类的坏例子。应该首选带有 HttpClient 的 NewtonSoft.Json
  • 感谢您的快速回复,@Cam

标签: c# rest endpoints


【解决方案1】:

问题是您将库的选项与 HTTP 标头混合在一起。试试这个:

public static void Main (string[] args)
{
    string url = "https://dashboard.reviewpush.com/api/company/locations";

    using (var client = new WebClient())
    {
        client.Headers[HttpRequestHeader.ContentType] = "application/json";
        client.Headers["X-Api-Key"] = "key";
        client.Headers["X-Api-Secret"] = "secret";

        string s = client.DownloadString(url);
        Console.WriteLine(s);
    }
}

如果您可以使用 .NET 4.5 或更高版本,您可能需要查看推荐的 HttpClient

【讨论】:

  • 感谢哥们的快速修复,我实际上是在混淆 OPTIONS 和标题。
猜你喜欢
  • 2022-07-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-30
  • 2020-01-03
  • 1970-01-01
  • 1970-01-01
  • 2016-01-02
相关资源
最近更新 更多