具有多个令牌的Httpclient授权

时间:2017-11-02 03:38:20

标签: c# multithreading dotnet-httpclient

我有不同的秘密密钥来验证一个网址。我不想为每个授权创建多个httpClient。有没有办法可以在httpClient的一个对象中发送多个密钥?或者我可以使用多线程中的所有密钥并行验证URL?

string baseAdd = "some url";
    string[] secretKeys = new string[] { "key1", "key2", "key3"};
    HttpClient client = new HttpClient { BaseAddress = new Uri(baseAdd) };
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new 
    MediaTypeWithQualityHeaderValue("application/json"));
    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", secretKey[0]);
    var content = new FormUrlEncodedContent(new[]{new KeyValuePair<string, string>("login", "login")
                });
    response = await client.PostAsync(url, content).ConfigureAwait(false);

1 个答案:

答案 0 :(得分:2)

DefaultRequestHeaders就是这样:通过HttpClient发送的任何请求的默认标头。正如“默认”所暗示的那样,它们可以在其他地方设置。像PostAsync(...)这样的方法只是创建请求对象并通过SendAsync(message)发送它的包装器。

所以你可以简单地静态地定义HttpClient:

static HttpClient client = new HttpClient(); 

然后创建消息并将标题应用于此。

HttpRequestMessage message = new HttpRequestMessage(HttpMethod.Post, "http://www.site.tld/blah");
message.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", "Moo");
message.Content = new StringContent("{\"a\": 5}", System.Text.Encoding.UTF8, "application/json");
var result = await client.SendAsync(message);