简体   繁体   English

如何访问API响应的内容?

[英]How do I access the content of an API response?

I've tried implementing the simplest case of this with a call to Mandrill's API using the method "ping." 我试过实现的简单的情况下使用方法与对山魈的API的调用“平”。 The response should be pong. 回应应该是傍晚。 Using a valid key, the response seems to work. 使用有效的密钥,响应似乎有效。 However, I am having trouble accessing the content of the response. 但是,我在访问响应的内容时遇到了麻烦。

The code is as follows: 代码如下:

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

How do I unpack the response from the call? 如何从通话中解包? Ultimately, I need to harvest emails from the server using the API, so I'll need to somehow preserve the structure of the json objects so I can access the details of the email. 最终,我需要使用API​​从服务器中收集电子邮件,因此我需要以某种方式保留json对象的结构,以便可以访问电子邮件的详细信息。

If you just want to read the response as a string: 如果只想将响应读取为字符串:

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

If you want to deserialize to some class (in this case the type MyClass ): 如果要反序列化某些类(在本例中为MyClass类型):

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

我将使用JSON.Net之类的东西将其序列化为可以使用的C#对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM