C# HttpClient请求post添加header

public string Post(string url, string postData = null, string contentType = null, Dictionary<string, string> headers = null, int timeOut = 30)
{
postData = postData ?? "";
using (HttpClient client = new HttpClient())
{
if (headers != null)
{
foreach (var header in headers)
client.DefaultRequestHeaders.Add(header.Key, header.Value);

}

using (HttpContent httpContent = new StringContent(postData, Encoding.UTF8))
{
if (contentType != null)
httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(contentType);

HttpResponseMessage response = client.PostAsync(url, httpContent).Result;
return response.Content.ReadAsStringAsync().Result;
}
}
}

添加授权认证:Bearer和认证内容
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", 认证数据);

posted @ 2025-06-27 17:22  jechsky1  阅读(406)  评论(0)    收藏  举报