在C#中设置HTTP请求的Authorization头部通常涉及使用HttpClient类。这里有一个简单的例子,展示了如何使用基本认证设置Authorization头部:

using System;
using System.Net.Http;
using System.Text;
 
class Program
{
static async Task Main(string[] args)
{
using (var httpClient = new HttpClient())
{
// 设置请求的目标地址
var url = "http://example.com";
 
// 创建基本认证的用户名和密码
string username = "user";
string password = "pass";
string credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes($"{username}:{password}"));
 
// 添加Authorization头部
httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", credentials);
 
// 发送GET请求
HttpResponseMessage response = await httpClient.GetAsync(url);
 
// 输出响应内容
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
}
}

在这个例子中,我们首先创建了一个HttpClient实例,然后使用Base64对用户名和密码进行编码以创建认证信息。接着,我们将这个认证信息添加到Authorization头部中,并发送一个GET请求。

如果你需要使用其他认证机制,比如Bearer Token,你可以修改AuthenticationHeaderValue的构造函数参数来匹配相应的认证类型,例如:

httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", "your_token_here");