c# - 使用 httpclient 在 C# 中获取 API 数据

标签 c# json api

我刚刚开始使用 API,并进行全面披露...我从这个答案中复制并粘贴:How do I make calls to a REST api using c#? 但很明显,我几乎迷路了。

我试图通过从 Dropbox API 获取信息来简单地开始。

我插入了 api URL,但我不知道如何传入身份验证 token 或帐户 ID。

private const string URL = "https://api.dropboxapi.com/2-beta-2/users/get_current_account";
        private const string urlParameters = "access_token=xxxxxxxxxxxxx";

        static void Main(string[] args)
        {
            HttpClient client = new HttpClient();
            client.BaseAddress = new Uri(URL);

            // Add an Accept header for JSON format.
            client.DefaultRequestHeaders.Accept.Add(
            new MediaTypeWithQualityHeaderValue("application/json"));

            // List data response.
            HttpResponseMessage response = client.GetAsync(urlParameters).Result;  // Blocking call!
            if (response.IsSuccessStatusCode)
            {
                // Parse the response body. Blocking!
                var dataObjects = response.Content.ReadAsAsync<IEnumerable<DataObject>>().Result;
                foreach (var d in dataObjects)
                {
                    Console.WriteLine("{0}", d.Name);
                    Console.ReadKey();
                }
            }

来自 Dropbox 的 http 请求应该是:

POST /2-beta-2/users/get_account
Host: https://api.dropboxapi.com
User-Agent: api-explorer-client
Authorization: Bearer xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx-xxxxxxxxxxxxxxxx
Content-Type: application/json

{
    "account_id": "dbid:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
}

最佳答案

您可能需要将 Bearer token 添加到请求中的 Headers

client.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken);

关于c# - 使用 httpclient 在 C# 中获取 API 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33155364/

相关文章:

c# - 不同数据库的事务

json - 将键值对附加到 json 对象

java - 使用 guava Function 接口(interface) vs 引入新类型

c# - 在类级别配置 Json.NET 序列化设置

php - 使用 Javascript 将多个表单数据收集为 JSON 并通过 AJAX 发送到 PHP

javascript - 网站页面加载时如何调用 API?

php - 从 Guzzle 中捕获异常

c# - 入口点不能用 'async' 修饰符标记

c# - 数据流管道中的全局每 block 错误处理

C#函数重载规则