我的 HttpClient.SendAsync 有问题,我尝试发送带有
POST
标头的 Authorization
请求,但是发送时它没有标头数据,这是我的发送请求代码:
static readonly HttpClient Client = new HttpClient();
string data = "{\"key\":\"value\"}";
long responseCode = -1;
string stringContent = string.Empty;
string authorizationToken = "secret";
using (var webRequest = new HttpRequestMessage(HttpMethod.Post, url))
{
webRequest.Headers.Authorization = new AuthenticationHeaderValue("Bearer", authorizationToken);
webRequest.Content = new StringContent(data, Encoding.UTF8, "application/json");
try
{
using var resp = await Client.SendAsync(webRequest);
{
responseCode = (long)resp.StatusCode;
stringContent = await resp.Content.ReadAsStringAsync();
}
Debug.WriteLine($"[Info] POST Result {id} {responseCode} {stringContent}");
}
catch (Exception ex)
{
Debug.WriteLine($"[Error] Cannot POST: {url} {ex.Message}");
}
}
网络服务端的代码
<?php
print_r(getallheaders());
当我使用其他客户端(例如
Insomnia
)时,其结果具有预期的标题
Array
(
[Host] => localhost
[User-Agent] => insomnia/2022.6.0
[Content-Type] => application/x-www-form-urlencoded
[Authorization] => Bearer hello
[Accept] => */*
)
但是对于
HttpClent
它只显示
Array
(
[Host] => localhost
)
它是控制台应用程序项目。