设置 HttpClient 的授权头

Set Authorization Header of HttpClient

我有以下代码,我想将 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);

抛出以下异常

An exception of type 'System.FormatException' occurred in System.Net.Http.dll but was not handled in user code

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

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

我遇到了同样的问题,我使用 :

解决了
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(endPoint);

request.Headers["Authorization"] = "Basic jMxMTgwMWUzYWFkYTk4NjM2MjcyOTk3MDowYTU0N2I2NzliNWRkMjliN2I4NTFlMDBkY2Y2NjQzNzQ5OTIxYzZl";

其中Basic后的字符串是来自Postman的编码字符串,选项为'code'。

希望对您有所帮助!

不确定这是否仍然是 运行,但基本授权密钥和类似 64 哈希授权密钥的内容将添加到类似 REST 调用的内容中,例如:

var httpClient2 = new HttpClient();
var uri = new Uri("<someuri>");
var tokenKey = "<sometokenkey>");
var httpContent = new StringContent("<some body or serialized thing>", System.Text.Encoding.UTF8, "application/json");

httpClient2.BaseAddress = new Uri(uri);
httpClient2.DefaultRequestHeaders.Accept.Clear();
httpClient2.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
httpClient2.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", tokenKey);

response = await httpClient2.PostAsync(uri, httpContent);