简体   繁体   中英

HttpClient GET Request

If I wanted to do a GET request for an API I want to use: https://mymarketnews.ams.usda.gov/mars-api/authentication how do I incorporate the authentication part to use my key for the request?

I am fairly new to this so I have been reading the documentation on HTTP client ( http://zetcode.com/csharp/httpclient/ ) and found what I think is what I am shooting for (C# HttpClient JSON request):

using System;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using Newtonsoft.Json;

namespace HttpClientJson
{
    class Contributor
    {
        public string Login { get; set; }
        public short Contributions { get; set; }

        public override string ToString()
        {
            return $"{Login,20}: {Contributions} contributions";
        }
    }

    class Program
    {
        private static async Task Main()
        {
            using var client = new HttpClient();

            client.BaseAddress = new Uri("https://api.github.com");
            client.DefaultRequestHeaders.Add("User-Agent", "C# console program");
            client.DefaultRequestHeaders.Accept.Add(
                    new MediaTypeWithQualityHeaderValue("application/json"));

            var url = "repos/symfony/symfony/contributors";
            HttpResponseMessage response = await client.GetAsync(url);
            response.EnsureSuccessStatusCode();
            var resp = await response.Content.ReadAsStringAsync();

            List<Contributor> contributors = JsonConvert.DeserializeObject<List<Contributor>>(resp);
            contributors.ForEach(Console.WriteLine);
        }
    }
} 

So my exact question is basically: In this type of JSON GET request, if I wanted to use this for my case would it be:

client.BaseAddress = new Uri("https://mymarketnews.ams.usda.gov");
var url = "https://marsapi.ams.usda.gov/services/v1.1/reports -H "Basic<Base64EncodedApiKey:>"";

where URL handles the bearer authentication? Or would that be in class contributor, I'm not sure i'd need that class in my case.

You would want to set the Authorization header of your HttpClient. So, using your example, you could add the following to your client setup:

client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", "Your Base64 Encoded API key");

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