HttpClient GET Request



如果我想为API执行GET请求,我想使用:https://mymarketnews.ams.usda.gov/mars-api/authentication如何合并身份验证部分以将密钥用于请求?

我对此还很陌生,所以我一直在阅读HTTP客户端上的文档(http://zetcode.com/csharp/httpclient/)并找到了我认为的目标(C#HttpClient JSON请求(:

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

所以我的确切问题基本上是:在这种类型的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:>"";

URL在哪里处理承载身份验证?或者这会是课堂上的贡献者吗?我不确定在我的情况下我是否需要那个课堂。

您需要设置HttpClient的Authorization头。因此,使用您的示例,您可以将以下内容添加到客户端设置中:

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

最新更新