c# - HttpClient GET 请求
问题描述
如果我想对我想使用的 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");
推荐阅读
- python-2.7 - python由用户写入输入而没有脏字符
- textmate - 具有多个值的范围属性
- c++ - 具有使用 operator<< 并打印错误值 c++ 的类的程序
- php - php中的Rtrim删除最后
- javascript - 旋转嵌套 SVG
- javascript - Javascript - 将 UTC 时间转换为特定时区
- r - 使用 Google 翻译 API 和 translateR,文件中的错误(con,“r”):无法打开连接
- vb.net - NumberOfPages 仅返回 1 页而不是 PDF 的 16 页
- shell - 获取没有唯一数据的证书指纹
- c# - 创建一个基于 SOAP 的 Web 服务,将数据从请求存储到数据库