private void AccessToken(APISettings apiSettings = null) { _client.DefaultRequestHeaders.Clear(); _client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "token"); request.Content = new FormUrlEncodedContent(new List <KeyValuePair <string, string> >() { new KeyValuePair <string, string>("grant_type", "client_credentials"), new KeyValuePair <string, string>("client_id", apiSettings.ClientId), new KeyValuePair <string, string>("client_secret", apiSettings.ClientSecret) }); var responseTask = _client.SendAsync(request); while (!responseTask.IsCompleted) { } var result = responseTask.Result; if (result.IsSuccessStatusCode) { var access_token = JsonConvert.DeserializeObject <dynamic>(result.Content.ReadAsStringAsync().Result); apiSettings.Access_Token = access_token["access_token"]; apiSettings.Refresh_Token = access_token["refresh_token"]; apiSettings.ExpireAccessToken = DateTime.Parse(access_token[".expires"].ToString()); apiSettings.SaveSettings(); } }
private void RefreshToken(APISettings apiSettings) { _client.DefaultRequestHeaders.Clear(); _client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "token"); request.Content = new FormUrlEncodedContent(new List <KeyValuePair <string, string> >() { new KeyValuePair <string, string>("grant_type", "refresh_token"), new KeyValuePair <string, string>("refresh_token", apiSettings.Refresh_Token) }); _client.SendAsync(request) .ContinueWith(responseTask => { if (responseTask.IsCompleted) { var result = responseTask.Result; if (result.IsSuccessStatusCode) { var access_token = JsonConvert.DeserializeObject <dynamic>(result.Content.ReadAsStringAsync().Result); apiSettings.Access_Token = access_token["access_token"]; apiSettings.ExpireAccessToken = DateTime.Parse(access_token[".expires"].ToString()); apiSettings.SaveSettings(); } else if (result.StatusCode == System.Net.HttpStatusCode.BadRequest) { AccessToken(apiSettings); } } }); _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiSettings.Access_Token); }