简体   繁体   中英

Get API data in C# with httpclient

I'm just starting out with APIs, and full disclosure... I copy and pasted from this answer: How do I make calls to a REST api using c#? But clearly I'm pretty much lost.

I'm trying to start simple by just getting info from the dropbox api.

I plugged in the api URL but I cannot figure out how to pass in the authentication token or the account 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();
                }
            }

from Dropbox the http request should be:

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令牌添加到请求中的Headers

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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