/// <summary> /// HttpClientの生成 /// </summary> /// <param name="clientType"></param> /// <returns></returns> private static HttpClient CreateHttpClient(ClientAcceptType clientType) { HttpClient client = new HttpClient(); switch (clientType) { case ClientAcceptType.Json: client.DefaultRequestHeaders.Remove("Accept"); client.DefaultRequestHeaders.Add("Accept", "application/json"); break; } return(client); }
/// <summary> /// 認証トークンを更新 /// </summary> /// <param name="url"></param> /// <param name="clientType"></param> public static void UpdateAuthorizationHeader(string url, ClientAcceptType clientType, AuthenticationStruct?authenticationData) { Uri uri = new Uri(url); string domain = uri.GetLeftPart(UriPartial.Authority); HttpClient client = clientList[domain][clientType]; if (authenticationData.HasValue) { // トークン再発行 var authHeader = GetAuthenticationHeader(authenticationData.Value); client.DefaultRequestHeaders.Remove("Authorization"); client.DefaultRequestHeaders.Add("Authorization", authHeader); } }
/// <summary> /// 使用できるHttpClientを取得 /// </summary> /// <param name="url"></param> /// <param name="clientType"></param> /// <param name="authenticationData">アクセス認証用設定値</param> /// <returns></returns> public static HttpClient GetHttpClient(string url, ClientAcceptType clientType, AuthenticationStruct?authenticationData = null) { Uri uri = new Uri(url); string domain = uri.GetLeftPart(UriPartial.Authority); // ドメインのリサイクル設定が行われているか確認 if (!domainList.ContainsKey(domain)) { // コネクションの自動リサイクル設定 var sp = ServicePointManager.FindServicePoint(new Uri(domain)); sp.ConnectionLeaseTimeout = 60 * 1000; // 1 minute lock (domainList) { domainList.Add(domain, 0); } lock (clientList) { // ドメイン・タイプごとのリストを作成 clientList.Add(domain, new Dictionary <ClientAcceptType, HttpClient>()); foreach (ClientAcceptType type in Enum.GetValues(typeof(ClientAcceptType))) { clientList[domain].Add(type, null); } } } // 同じドメイン・ClientTypeのHttpClientを取得、存在しなければ生成 HttpClient client = clientList[domain][clientType]; if (client == null) { client = CreateHttpClient(clientType); if (authenticationData.HasValue) { // 値が指定されていれば認証実施 var authHeader = GetAuthenticationHeader(authenticationData.Value); client.DefaultRequestHeaders.Add("Authorization", authHeader); } clientList[domain][clientType] = client; } return(client); }