/// <summary>Makes request based on httpMethod</summary> /// <param name="uri">Request URL</param> /// <param name="parameters">Request URL parameters</param> /// <param name="httpMethod">HTTP method (GET, POST etc)</param> /// <param name="httpHeaders">Request headers</param> /// <param name="body">Request body</param> /// <param name="contentType">Content-Type HTTP header</param> /// <param name="accept">Accept HTTP header</param> /// <param name="timeout">Request timeout</param> /// <param name="compressBody">Compresses request using GZIP</param> /// <param name="maxAttempts">Maximum number of times to attempt the request. Cannot be less than 1.</param> /// <exception cref="RESTCallerException">Thrown when any error happened.</exception> public RestCallerResponse MakeRequest(Uri uri, string httpMethod, IReadOnlyDictionary <string, string> parameters = null, IReadOnlyDictionary <string, string> httpHeaders = null, string body = null, string contentType = "application/json; charset=utf-8", string accept = "application/json", int timeout = 1 * 60 * 1000, bool compressBody = false, int maxAttempts = 1) { Check.ArgumentIsNull(uri, "uri"); Check.ArgumentIsNullOrWhiteSpace(httpMethod, "httpMethod"); Check.ArgumentIsNullOrWhiteSpace(contentType, "contentType"); Check.ArgumentIsNullOrWhiteSpace(accept, "accept"); Check.Argument(timeout >= 0, "timeout >= 0"); Check.Argument(maxAttempts >= 1, "maxAttempts >= 1"); var attemptErrors = new List <WebException>(); try { while (true) { if (parameters != null && parameters.Any()) { uri = uri.ComposeUri(parameters); } try { var webRequest = CreateWebRequest(uri, httpMethod, contentType, accept, timeout); AddHttpHeaders(webRequest, httpHeaders, compressBody); if (!string.IsNullOrWhiteSpace(body)) { if (compressBody) { using (var requestStream = webRequest.GetRequestStream()) { using (var gzipStream = new GZipStream(requestStream, CompressionMode.Compress)) { using (var streamWriter = new StreamWriter(gzipStream)) { streamWriter.Write(body); } } } } else { using (var requestStream = webRequest.GetRequestStream()) { using (var streamWriter = new StreamWriter(requestStream)) { streamWriter.Write(body); } } } } using (var webResponse = (HttpWebResponse)webRequest.GetResponse()) { return(GetResponse(webResponse, attemptErrors)); } } catch (WebException ex) { attemptErrors.Add(ex); if (attemptErrors.Count < maxAttempts && _retryStrategy.IsTransient(ex)) { Thread.Sleep(WAIT_TIMEOUT_IN_MILLISECONDS_AFTER_FIRST_ATTEMPT * attemptErrors.Count); continue; } var response = ex.Response; if (response == null) { throw; } using (var webResponse = (HttpWebResponse)response) { return(GetResponse(webResponse, attemptErrors)); } } } } catch (Exception ex) { throw new RESTCallerException("REST Caller Error.", ex, attemptErrors); } }
public void Status_IsTransient(WebExceptionStatus status) { var ex = new WebException(status.ToString(), status); Assert.IsTrue(_retryStrategy.IsTransient(ex)); }