如何调用第三方RestfulAPI

How to call third party Restful API

我们如何在 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());

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

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

问题是您将库的选项与 HTTP headers 混淆了。试试这个:

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