设置HttpClient的授权头

人气:366 发布:2022-10-16 标签: authorization c# httpclient httpcontent

问题描述

我有以下代码,我想将POST请求的授权设置为如下所示:

Authorization:key=somevalue

using (HttpClient client = new HttpClient())
{
     using (StringContent jsonContent = new StringContent(json))
     {
         jsonContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");

         using (HttpResponseMessage response = await client.PostAsync("https://android.googleapis.com/gcm/send", jsonContent))
         {
            var reponseString = await response.Content.ReadAsStringAsync();
         }
     }
}

如何操作?我真的很挣扎 和以下语句

client.DefaultRequestHeaders.Add("Authorization", "key=" + apiKey);

引发以下异常

在中发生了类型为‘System.FormatException’的异常 System.Net.Http.dll,但未在用户代码中处理

推荐答案

我通过下面一行代码解决了这个问题。

client.DefaultRequestHeaders.Authorization =
       new AuthenticationHeaderValue("key", "=" + apiKey);

328