public static string MakeHttpWebRequest(string requestUrl, string apiKey, TeamSupport.Data.Logs log, Settings settings, string apiCallCountKey, ref int currentApiCallCount) { string responseText = string.Empty; HttpWebRequest request = WebRequest.Create(requestUrl) as HttpWebRequest; request.ContentType = "application/json"; request.Headers.Add(String.Format("X-FullContact-APIKey:{0}", apiKey)); try { using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) { if (response.StatusCode != HttpStatusCode.OK && response.StatusCode != HttpStatusCode.Accepted) { throw new Exception(String.Format( "Error when connecting to FullContact: Server error (HTTP {0}: {1}).", response.StatusCode, response.StatusDescription)); } currentApiCallCount++; settings.WriteInt(apiCallCountKey, currentApiCallCount); using (var reader = new StreamReader(response.GetResponseStream(), ASCIIEncoding.UTF8)) { responseText = reader.ReadToEnd(); } if (response.StatusCode == HttpStatusCode.Accepted || (responseText.Contains("status") && responseText.Contains("202") && responseText.Contains("Queued") && responseText.Contains("retry"))) { log.WriteEvent(responseText); responseText = null; } // Get the headers associated with the response. WebHeaderCollection headerCollection = response.Headers; String[] remaining = headerCollection.GetValues(RateLimitHeaders.Remaining.GetDescription()); String[] reset = headerCollection.GetValues(RateLimitHeaders.Reset.GetDescription()); String[] limit = headerCollection.GetValues(RateLimitHeaders.Limit.GetDescription()); string rateLimitHeadersString = string.Empty; if (limit.Any() && limit.Length > 0) { rateLimitHeadersString = string.Format("{0}: {1}", RateLimitHeaders.Limit.GetDescription(), limit[0]); } if (reset.Any() && reset.Length > 0) { rateLimitHeadersString += string.Format("\t{0}: {1}", RateLimitHeaders.Reset.GetDescription(), reset[0]); } if (remaining.Any() && remaining.Length > 0) { rateLimitHeadersString += string.Format("\t{0}: {1}", RateLimitHeaders.Remaining.GetDescription(), remaining[0]); log.WriteEvent(rateLimitHeadersString); int remainingCount = int.Parse(remaining[0]); if (remainingCount == 1) { //wait if (reset.Any() && reset.Length > 0) { int resetSeconds = int.Parse(reset[0]); log.WriteEvent(string.Format("Rate Limit reached. Sleeping {0} seconds until it resets.", resetSeconds)); System.Threading.Thread.Sleep(resetSeconds * 1000); log.WriteEvent("After sleep. Continuing..."); } } } else { log.WriteEvent(rateLimitHeadersString); } } } catch (WebException webEx) { log.WriteEvent(requestUrl); log.WriteException(webEx); } catch (Exception ex) { log.WriteException(ex); } return(responseText); }