【问题标题】:How do I access the content of an API response?如何访问 API 响应的内容?
【发布时间】:2015-07-23 18:04:12
【问题描述】:

我尝试使用“ping”方法调用 Mandrill 的 API 来实现 this 的最简单情况。响应应该是乒乓球。使用有效的密钥,响应似乎有效。但是,我无法访问响应的内容。

代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;
using System.Net.Http.Headers;

namespace MandrillAPI
{
    class Program
    {
        static void Main(string[] args)
        {
            string ping = "https://mandrillapp.com/api/1.0/users/ping.json";
            string key = "?key=123";
            HttpClient client = new HttpClient();
            client.BaseAddress = new Uri(ping);
            HttpResponseMessage response = client.GetAsync(key).Result;
            Console.WriteLine(response.ToString());
            Console.Read();
        }
    }
}

如何解压来自呼叫的响应?最终,我需要使用 API 从服务器收集电子邮件,因此我需要以某种方式保留 json 对象的结构,以便访问电子邮件的详细信息。

【问题讨论】:

  • 您能否详细说明您期望的结果是什么?

标签: c# asp.net json mandrill


【解决方案1】:

我会使用 JSON.Net 之类的东西将其序列化为一个 C# 对象,然后您可以使用它。

【讨论】:

    【解决方案2】:

    如果您只想将响应读取为字符串:

    string content = response.Content.ReadAsStringAsync().Result
    

    如果您想反序列化为某个类(在本例中为 MyClass 类型):

    MyClass myClass = JsonConvert.DeserializeObject<MyClass>(response.Content.ReadAsStringAsync().Result)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-08
      • 1970-01-01
      • 2021-08-06
      • 1970-01-01
      • 1970-01-01
      • 2016-05-27
      • 1970-01-01
      相关资源
      最近更新 更多