public async Task <T> SendHttpRequestAsync <T>(HttpMethod httpMethod, string relativeUri, object data = null) { T result = default; HttpRequestMessage httpRequest = CreateHttpRequest(httpMethod, relativeUri); if (data != null) { var jsonData = JsonConverterService.Serialize(data); var content = new StringContent(jsonData, Encoding.UTF8, "application/json"); httpRequest.Content = content; } using (var httpClient = HttpClientFactory.CreateClient(Constants.HttpClientDefault)) { using (var response = await httpClient.SendAsync(httpRequest)) { //Disable! otherwise HttpRequestException is thrown instead of MollieApiException //response.EnsureSuccessStatusCode(); result = await ProcessHttpResponseMessageAsync <T>(response); } } return(result); }
private async Task <T> ProcessHttpResponseMessageAsync <T>(HttpResponseMessage response) { var resultContent = await response.Content.ReadAsStringAsync(); if (response.IsSuccessStatusCode) { return(JsonConverterService.Deserialize <T>(resultContent)); } switch (response.StatusCode) { case HttpStatusCode.BadRequest: case HttpStatusCode.Unauthorized: case HttpStatusCode.Forbidden: case HttpStatusCode.NotFound: case HttpStatusCode.MethodNotAllowed: case HttpStatusCode.UnsupportedMediaType: case HttpStatusCode.Gone: case (HttpStatusCode)422: // Unprocessable entity throw new MollieApiException(resultContent); default: throw new HttpRequestException( $"Unknown http exception occured with status code: {(int)response.StatusCode}."); } }
public ClientService(string apiKey, HttpClient httpClient = null, IValidatorService validatorService = null) { if (string.IsNullOrWhiteSpace(apiKey)) { throw new ArgumentNullException(nameof(apiKey), "Mollie API key cannot be empty"); } _jsonConverterService = new JsonConverterService(); _httpClient = httpClient ?? new HttpClient(); _validatorService = validatorService ?? new ValidatorService(); ApiKey = apiKey; }