如何调用第三方Restful API

时间:2018-01-10 17:03:50

标签: c# rest endpoints

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

1 个答案:

答案 0 :(得分:0)

问题是您正在使用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