C#将token写入请求头中
时间: 2024-04-30 20:21:52 浏览: 165
在C#中,可以使用HttpClient类来发送HTTP请求,并将token写入请求头中。下面是一个示例代码:
```csharp
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
var client = new HttpClient();
client.BaseAddress = new Uri("https://example.com");
// 设置Authorization头
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "your_token_here");
// 发送GET请求
HttpResponseMessage response = await client.GetAsync("/api/resource");
// 处理响应
if (response.IsSuccessStatusCode)
{
string content = await response.Content.ReadAsStringAsync();
Console.WriteLine("Response content: " + content);
}
else
{
Console.WriteLine("Request failed with status code: " + response.StatusCode);
}
}
}
```
在上面的示例代码中,我们首先创建了一个HttpClient对象,并设置了请求的基地址。然后,我们在请求头中设置了Authorization头,并将token写入其中。最后,我们使用HttpClient发送GET请求,并处理响应。
阅读全文