简体   繁体   English

HttpClient GET 请求

[英]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?如果我想对 API 执行 GET 请求,我想使用: https://mymarketnews.ams.usda.gov/mars-api/authentication如何合并身份验证部分以将我的密钥用于请求?

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):我对此相当陌生,所以我一直在阅读有关 HTTP 客户端( http://zetcode.com/csharp/httpclient/ )的文档,并发现我认为是我正在拍摄的内容(C# HttpClient Z0ECD11C1D7A28740)

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:所以我的确切问题基本上是:在这种类型的 JSON GET 请求中,如果我想在我的情况下使用它,它会是:

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? URL 在哪里处理承载认证? Or would that be in class contributor, I'm not sure i'd need that class in my case.还是在 class 贡献者中,我不确定在我的情况下我是否需要 class。

You would want to set the Authorization header of your HttpClient.您需要设置 HttpClient 的授权 header。 So, using your example, you could add the following to your client setup:因此,使用您的示例,您可以将以下内容添加到客户端设置中:

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

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

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