public async Task PostBlogPostWithHeaderParameter() { var postToCreate = new BlogPost { Id = 1, Title = "A simple post title", Body = "A simple post", UserId = 1 }; var postToPostAsJson = JsonConvert.SerializeObject(postToCreate); var requestInfo = new RestClientRequest(BaseUri, "posts", bodyAsJson: postToPostAsJson); requestInfo.AddHeader(("TestHeader", "TestHeaderValue")); var restClientResponse = await RestClient .ExecuteWithExponentialRetryAsync <BlogPost>(HttpMethod.POST, false, 1, 1, HttpStatusCodesWorthRetrying, requestInfo) .ConfigureAwait(false); Assert.IsTrue(restClientResponse.StatusCode == HttpStatusCode.Created); Assert.IsTrue(restClientResponse.Result.Id == postToCreate.Id); Assert.IsTrue(restClientResponse.Result.Title == postToCreate.Title); Assert.IsTrue(restClientResponse.Result.Body == postToCreate.Body); Assert.IsTrue(restClientResponse.Result.UserId == postToCreate.UserId); Assert.IsTrue(requestInfo.HeaderParameters.FirstOrDefault().Key == "TestHeader"); Assert.IsTrue(requestInfo.HeaderParameters.FirstOrDefault().Value == "TestHeaderValue"); Assert.IsTrue(restClientResponse.Headers.Any()); }
private Task <IEnumerable <ServiceEmployeeDto> > GetAllServiceEmployeeDtoList(string baseUri, string allEmployeesResource) { var restClientRequest = new RestClientRequest(baseUri, allEmployeesResource); return(_restClient.ExecuteGetResultAsync <IEnumerable <ServiceEmployeeDto> >(restClientRequest)); }
public async Task PutBlogPost() { var postToPut = new BlogPost { Id = 1, Title = "A simple post title", Body = "A simple post", UserId = 1 }; var postToPutAsJson = JsonConvert.SerializeObject(postToPut); var requestInfo = new RestClientRequest(BaseUri, "posts/1", bodyAsJson: postToPutAsJson); var restClientResponse = await RestClient .ExecuteWithExponentialRetryAsync <BlogPost>(HttpMethod.PUT, false, 1, 1, HttpStatusCodesWorthRetrying, requestInfo) .ConfigureAwait(false); Assert.IsTrue(restClientResponse.StatusCode == HttpStatusCode.OK); Assert.IsTrue(restClientResponse.Result.Id == postToPut.Id); Assert.IsTrue(restClientResponse.Result.Title == postToPut.Title); Assert.IsTrue(restClientResponse.Result.Body == postToPut.Body); Assert.IsTrue(restClientResponse.Result.UserId == postToPut.UserId); Assert.IsTrue(restClientResponse.Headers.Any()); }
public async Task ExecuteAsync_UsesHttpClientBaseAddress() { // setup message handler var mockMessageHandler = new Mock <HttpMessageHandler>(MockBehavior.Strict); mockMessageHandler.Protected() .Setup <Task <HttpResponseMessage> >( "SendAsync", ItExpr.Is <HttpRequestMessage>(message => message.RequestUri.Equals(new Uri("https://hello.hello/test"))), ItExpr.IsAny <CancellationToken>() ) .ReturnsAsync(new HttpResponseMessage { StatusCode = HttpStatusCode.OK, Content = new StringContent("test"), }) .Verifiable(); // arrange var request = new RestClientRequest(HttpMethod.Get, "test"); var client = new RestClient(new HttpClient(mockMessageHandler.Object) { BaseAddress = new Uri("https://hello.hello") }); // act await client.ExecuteAsync(request); // assert mockMessageHandler.Verify(); }
private RestRequest BuildRestReqestObject(RestClientRequest requestObj) { var request = new RestRequest { Resource = requestObj._apiMethod }; if (requestObj._inputParameters == null || requestObj._inputParameters.Count <= 0) { return(request); } foreach (var inputParam in requestObj._inputParameters) { request.AddParameter(inputParam.Key, inputParam.Value, ParameterType.UrlSegment); } request.Method = Method.POST; //This could be parameterized from the client. For now we are only supporting get calls //This would be sent as input parameter. Just was lazy to hardcode it here string jsonToSend = @"xxxxxxxxxxx"; request.AddParameter("application/json; charset=utf-8", jsonToSend, ParameterType.RequestBody); return(request); }
public async Task <IRestResponse <T> > GetAsync <T>(RestClientRequest request) where T : new() { //Build the client object BuildRestClient(request); //Build request object var restRequest = BuildRestReqestObject(request); //var response11 = _httpClient.Execute<T>(restRequest); var taskSource = new TaskCompletionSource <IRestResponse <T> >(); //Execute the request _httpClient.ExecuteAsync <T>(restRequest, response => { if (response.ErrorException != null) { taskSource.TrySetException(response.ErrorException); } else { taskSource.TrySetResult(response); } }); return(await taskSource.Task); }
private static RestSharp.IRestClient GetRestClient(bool useHttp, RestClientRequest requestInfo) { var transferProtocol = useHttp ? "http://" : "https://"; var baseUri = $"{transferProtocol}{requestInfo.BaseUri}"; return(new RestSharp.RestClient(baseUri)); }
private void BuildRestClient(RestClientRequest request) { //Set the headers foreach (var header in request._requestHeaders) { _httpClient.AddDefaultHeader(header.Key, header.Value); } }
public async Task <UserModel> GetUserAsync(string username) { var request = new RestClientRequest <UserModel>(HttpMethod.Get, "v1/users"); request.AddQueryParameter("username", username); var response = await _client.ExecuteAsync(request).ConfigureAwait(false); return(response.Data); }
private static string SendPost(object input) { var _url = "https://realfavicongenerator.net/api"; var restClient = new RestClientRequest(_url, "favicon"); restClient.AddJsonParameter(input); var searchOutputs = restClient.SendPostRequest(); return(searchOutputs.Content); }
public void GetNotExistentResource() { var requestInfo = new RestClientRequest(BaseUri, "carrero"); var restClientException = Assert.ThrowsAsync <RestClientException>(() => RestClient .ExecuteWithExponentialRetryAsync <bool>(HttpMethod.GET, false, 3, 1, HttpStatusCodesWorthRetrying, requestInfo)); Assert.IsTrue(restClientException.ErrorResponse.StatusCode == HttpStatusCode.NotFound); }
public static (IRestClient, IRestRequest) GetRequestConfiguration(HttpMethod httpMethod, bool useHttp, RestClientRequest requestInfo) { Enum.TryParse <Method>(httpMethod.ToString(), out var restSharpHttpMethod); var restClient = GetRestClient(useHttp, requestInfo); var request = GetRestRequest(restSharpHttpMethod, requestInfo); return(restClient, request); }
private static void AddHeaderParameters(IRestRequest request, RestClientRequest requestInfo) { if (requestInfo.HeaderParameters == null) { return; } foreach (var headerParameter in requestInfo.HeaderParameters) { request.AddHeader(headerParameter.Key, headerParameter.Value); } }
public async Task ExecuteAsync_NoBaseAddress_ThrowsInvalidOperationException() { // setup message handler var mockMessageHandler = new Mock <HttpMessageHandler>(MockBehavior.Strict); // arrange var request = new RestClientRequest(HttpMethod.Get, "test"); var client = new RestClient(new HttpClient(mockMessageHandler.Object)); // act/assert await Assert.ThrowsAsync <InvalidOperationException>(() => client.ExecuteAsync(request)); }
private static void AddUriSegments(IRestRequest request, RestClientRequest requestInfo) { if (requestInfo.UriSegments == null) { return; } foreach (var uriSegment in requestInfo.UriSegments) { request.AddUrlSegment(uriSegment.Key, uriSegment.Value); } }
private static void AddQueryParameters(IRestRequest request, RestClientRequest requestInfo) { if (requestInfo.QueryParameters == null) { return; } foreach (var queryParameter in requestInfo.QueryParameters) { request.AddQueryParameter(queryParameter.Key, queryParameter.Value); } }
public void PutDeserializationError() { var requestInfo = new RestClientRequest(BaseUri, "posts/1"); var restClientException = Assert.ThrowsAsync <RestClientException>(() => RestClient .ExecuteWithExponentialRetryAsync <bool>(HttpMethod.PUT, false, 1, 1, HttpStatusCodesWorthRetrying, requestInfo)); Assert.IsTrue(restClientException.ErrorResponse.StatusCode == HttpStatusCode.OK); Assert.IsTrue(restClientException.ErrorResponse.ErrorException != null); Assert.IsTrue(!string.IsNullOrWhiteSpace(restClientException.ErrorResponse.ErrorMessage)); Assert.IsTrue(!string.IsNullOrEmpty(restClientException.ErrorResponse.ResponseContent)); }
private Task <ServiceEmployeeDto> GetSingleServiceEmployeeDto(int employeeId, string baseUri, string singleEmployeeResource) { var employeeIdUrlSegmentDictionary = new Dictionary <string, string> { { "employeeId", employeeId.ToString() } }; var restClientRequest = new RestClientRequest(baseUri, singleEmployeeResource, null, null, employeeIdUrlSegmentDictionary); return(_restClient.ExecuteGetResultAsync <ServiceEmployeeDto>(restClientRequest)); }
public async Task GetBlogPostWithNoParameters() { var requestInfo = new RestClientRequest(BaseUri, "posts/1"); var restClientResponse = await RestClient .ExecuteWithExponentialRetryAsync <BlogPost>(HttpMethod.GET, false, 1, 1, HttpStatusCodesWorthRetrying, requestInfo) .ConfigureAwait(false); Assert.IsTrue(restClientResponse.StatusCode == HttpStatusCode.OK); Assert.IsTrue(restClientResponse.Result != null); Assert.IsTrue(restClientResponse.Result.Id == 1); Assert.IsTrue(restClientResponse.Headers.Any()); }
public async Task <TResult> ExecuteGetResultAsync <TResult>(RestClientRequest requestInfo) { var restClient = GetRestClient(false, requestInfo); var request = GetRequest(Method.GET, requestInfo); var restResponse = await ExecuteGetWithResponseOrExceptionRetryPolicyAsync <TResult>(restClient, request, 3, 1) .ConfigureAwait(false); if (restResponse.IsSuccessful) { return(JsonConvert.DeserializeObject <TResult>(restResponse.Content)); } throw new Exception(restResponse.Content.Trim('"')); }
private static IRestRequest GetRequest(Method method, RestClientRequest requestInfo, int timeout = 3600000) { var request = new RestRequest(requestInfo.Resource, method); AddHeaderParameters(request, requestInfo); AddQueryParameters(request, requestInfo); AddUriSegments(request, requestInfo); if (requestInfo.BodyAsJson != null) { request.AddParameter("application/json", requestInfo.BodyAsJson, ParameterType.RequestBody); } request.Timeout = timeout; return(request); }
public async Task GetBlogPostWithHeaderParameter() { var requestInfo = new RestClientRequest(BaseUri, "posts/1"); requestInfo.AddHeader(("TestHeader", "TestHeaderValue")); var restClientResponse = await RestClient .ExecuteWithExponentialRetryAsync <BlogPost>(HttpMethod.GET, false, 1, 1, HttpStatusCodesWorthRetrying, requestInfo) .ConfigureAwait(false); Assert.IsTrue(restClientResponse.StatusCode == HttpStatusCode.OK); Assert.IsTrue(restClientResponse.Result != null); Assert.IsTrue(restClientResponse.Result.Id == 1); Assert.IsTrue(requestInfo.HeaderParameters.FirstOrDefault().Key == "TestHeader"); Assert.IsTrue(requestInfo.HeaderParameters.FirstOrDefault().Value == "TestHeaderValue"); Assert.IsTrue(restClientResponse.Headers.Any()); }
public async Task GetBlogPostWithUrlSegment() { var uriSegments = new Dictionary <string, string> { { "id", "1" } }; var requestInfo = new RestClientRequest(BaseUri, "posts/{id}", uriSegments: uriSegments); var restClientResponse = await RestClient .ExecuteWithExponentialRetryAsync <BlogPost>(HttpMethod.GET, false, 1, 1, HttpStatusCodesWorthRetrying, requestInfo) .ConfigureAwait(false); Assert.IsTrue(restClientResponse.StatusCode == HttpStatusCode.OK); Assert.IsTrue(restClientResponse.Result != null); Assert.IsTrue(restClientResponse.Result.Id == 1); Assert.IsTrue(restClientResponse.Headers.Any()); }
public Uri Webhook(string codeName, string token = null) { if (codeName == null) { throw new ArgumentNullException("codeName"); } IRestClientRequest request = new RestClientRequest { EndPoint = string.Format("{0}/webhook", EndPoint), AuthTokenLocation = AuthTokenLocation.Querystring, Query = new NameValueCollection { { "code_name", codeName } } }; return(RestClient.BuildRequestUri(_client.Config, request, token)); }
public async Task GetBlogPostWithQueryParameter() { var requestInfo = new RestClientRequest(BaseUri, "posts"); requestInfo.AddQueryParameter(("userId", "1")); var restClientResponse = await RestClient .ExecuteWithExponentialRetryAsync <IEnumerable <BlogPost> >(HttpMethod.GET, false, 1, 1, HttpStatusCodesWorthRetrying, requestInfo) .ConfigureAwait(false); Assert.IsTrue(restClientResponse.StatusCode == HttpStatusCode.OK); Assert.IsTrue(restClientResponse.Result != null); Assert.IsTrue(restClientResponse.Result.Any()); Assert.IsTrue(restClientResponse.Result.Count(blogPost => blogPost.UserId == 1) == restClientResponse.Result.Count()); Assert.IsTrue(restClientResponse.Headers.Any()); }
/// <exception cref="T:RestClientSDK.Entities.RestClientException"> /// If something fails with the call or with the /// serialization. /// </exception> public async Task <RestClientResponse <TResult> > ExecuteWithExponentialRetryAsync <TResult>(HttpMethod httpMethod, bool useHttp, int maxRetryAttempts, int retryFactor, HttpStatusCode[] httpStatusCodesWorthRetrying, RestClientRequest requestInfo) { var(client, request) = Request.GetRequestConfiguration(httpMethod, useHttp, requestInfo); var restResponse = await ExecuteRequestWithRetryPolicyAsync <TResult>(httpMethod, maxRetryAttempts, retryFactor, httpStatusCodesWorthRetrying, client, request).ConfigureAwait(false); if (restResponse.IsSuccessful) { return(new RestClientResponse <TResult>(restResponse.Data, restResponse.StatusCode, Response.GetHeaders(restResponse))); } var resClientErrorResponse = new RestClientErrorResponse(restResponse.StatusCode, restResponse.Content, restResponse.ErrorMessage, restResponse.ErrorException); throw new RestClientException(resClientErrorResponse); }