设置HttpClient的授权标头

时间:2015-08-23 14:36:24

标签: c# authorization 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但未在用户代码中处理

3 个答案:

答案 0 :(得分:18)

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

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

答案 1 :(得分:0)

不确定这是否仍在运行,但基本身份验证密钥和诸如 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);

答案 2 :(得分:-1)

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

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

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

Basic之后的字符串是Postman的编码字符串,选项为'code'。

我希望这会有所帮助!