【问题标题】:Read New Relic json message阅读 New Relic json 消息
【发布时间】:2014-01-30 09:32:18
【问题描述】:

我几乎没有附加到新遗物的应用程序。当我输入我的 api 密钥并点击发送请求时,我会收到 json 格式的回复。

curl -X GET 'https://api.newrelic.com/v2/applications.json' \ -H 'X-Api-Key:<api key>' -i

这就是请求的内容。我不知道上面的代码是什么。好吧,我需要在 C# 中读取返回的 json 消息,然后可能会反序列化 json 消息。

我试过了

 public ActionResult Index()
    {
        WebRequest wr = WebRequest.Create("https://api.newrelic.com/v2/applications.json");

        wr.ContentType = "application/json";
        wr.Method = "GET";
        //wr.Headers["X-Parse-REST-API-Key"] = "<my api key>";
        wr.Headers.Add("Authorization", "<my api key>");

        using (WebResponse response = wr.GetResponse())
        {
            using (Stream stream = response.GetResponseStream())
            {
                int x = 10;
            }
        }

但我收到 500 错误。

【问题讨论】:

  • 请解释一下您要做什么。您的问题应该更具体...如果我们不知道您要做什么以及为什么它对您失败,就不可能理解您的问题。
  • @JotaBe 我有一个 curl 命令。如何将其转换为 c# 代码? curl命令写在上面和下面是我尝试过的c#代码

标签: c# json asp.net-mvc-4 newrelic


【解决方案1】:

您的代码非常接近工作。您只需如下所示稍微更改您的请求标头(并替换您自己的 api 密钥)。然后,正如您所说,您将需要反序列化 json。我已经测试了这段代码,它返回了 curl 命令的等价物。

    WebRequest wr = WebRequest.Create("https://api.newrelic.com/v2/applications.json");
    wr.ContentType = "application/json";
    wr.Method = "GET";
    wr.Headers.Add("X-Api-Key:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");

    using (WebResponse response = wr.GetResponse())
    {
        using (Stream stream = response.GetResponseStream())
        {
            byte[] bytes = new Byte[10000];
            int n = stream.Read(bytes, 0, 9999);
            string s = System.Text.Encoding.ASCII.GetString(bytes);
        }
    }

您可能知道,您可以使用我们的 api explorer 来形成提取您感兴趣的数据所需的 http 请求。然后您应该能够将请求从 api explorer 复制到您的 c# 代码。请参阅此处的 api explorer 文档:https://docs.newrelic.com/docs/features/getting-started-with-new-relics-api-explorer

【讨论】:

    猜你喜欢
    • 2013-03-07
    • 2013-07-05
    • 1970-01-01
    • 1970-01-01
    • 2010-12-23
    • 2012-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多