private async Task <HttpRequestMessage> GetRestRequest(HttpMethod httpMethod, string relativeUrl, PostContentBase bodyContent, CancellationToken cancellationToken) { // Create HTTP transport objects var httpRequest = new HttpRequestMessage { Method = httpMethod, RequestUri = new Uri(HttpClient.BaseAddress, relativeUrl) }; var jsonObj = SafeJsonConvert.SerializeObject(bodyContent, SerializationSettings); httpRequest.Content = new StringContent(jsonObj, Encoding.UTF8, "application/json"); if (_credentials != null) { await _credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); } return(httpRequest); }
public async Task <T> ExecuteRestMethod <T>(HttpMethod httpMethod, string relativePath, PostContentBase bodyContent, CancellationToken cancellationToken, EventHandler <SentHttpRequest> sentHttpRequestHandler, EventHandler <ReceivedHttpResponse> receivedHttpRequestHandler) { using (var request = await GetRestRequest(httpMethod, relativePath, bodyContent, cancellationToken)) { sentHttpRequestHandler?.Invoke(this, new SentHttpRequest(HttpMethod.Post, request.RequestUri, request.Content)); using (var response = await HttpClient.SendAsync(request, cancellationToken)) { var content = await response.Content.ReadAsStringAsync() .WithCancellation(cancellationToken).ConfigureAwait(false); receivedHttpRequestHandler?.Invoke(this, new ReceivedHttpResponse(content)); var responseBody = DeserializeResponse <T>(response.StatusCode, content); return(responseBody); } } }