Created
October 9, 2013 09:46
-
-
Save JakeGinnivan/6898824 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public class HttpExecutor : IHttpExecutor | |
| { | |
| private readonly HttpClient _restClient; | |
| public EmbedApi(IConfig config, Func<Owned<ILifetimeScope>> lifetimeScope) | |
| { | |
| var scope = lifetimeScope().Value; | |
| var httpClientHandler = new HttpClientHandler | |
| { | |
| Credentials = new NetworkCredential(config.Username, config.Password) | |
| }; // Example setting stuff up | |
| var baseUri = config.ApiBaseUri; | |
| baseUri = baseUri.EndsWith("/") ? baseUri : baseUri + "/"; | |
| _restClient = new HttpClient(httpClientHandler) | |
| { | |
| BaseAddress = new Uri(baseUri) | |
| }; | |
| _restClient.DefaultRequestHeaders.Accept.Clear(); | |
| _restClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); | |
| } | |
| public async Task Execute(IHttpCall httpCall) | |
| { | |
| var httpResponse = await httpCall.Execute(_restClient); | |
| if (!httpResponse.IsSuccessStatusCode) | |
| { | |
| Trace.TraceError("Failed to call to url {3} ({2}.cs), error: {0}\r\n\r\nContent:\r\n{1}", httpResponse.ReasonPhrase, | |
| await httpResponse.Content.ReadAsStringAsync(), httpCall.GetType().Name, | |
| httpResponse.RequestMessage.RequestUri.ToString()); | |
| var exception = new ApiCallFailedException(httpResponse.ReasonPhrase, httpResponse.StatusCode); | |
| ReportErrorToCentral(exception, embedApiCall); | |
| throw exception; | |
| } | |
| } | |
| public async Task<T> Execute<T>(IHttpCallWithResult<T> httpCallWithResult) where T : class | |
| { | |
| var httpResponse = await httpCallWithResult.Execute(_restClient); | |
| if (httpResponse.StatusCode == HttpStatusCode.NotFound) | |
| return null; | |
| string error; | |
| if (httpResponse.IsSuccessStatusCode) | |
| { | |
| try | |
| { | |
| return await httpResponse.Content.ReadAsAsync<T>(); | |
| } | |
| catch (JsonSerializationException ex) | |
| { | |
| error = ex.Message; | |
| } | |
| } | |
| else | |
| { | |
| error = httpResponse.ReasonPhrase; | |
| } | |
| Trace.TraceError("Failed to call to url {3} ({2}.cs), error: {0}\r\n\r\nContent:\r\n{1}", error, | |
| await httpResponse.Content.ReadAsStringAsync(), httpCallWithResult.GetType().Name, | |
| httpResponse.RequestMessage.RequestUri.ToString()); | |
| var exception = new ApiCallFailedException(error, httpResponse.StatusCode); | |
| ReportErrorToCentral(exception, httpCallWithResult); | |
| throw exception; | |
| } | |
| private void ReportError(Exception e, IHttpCall embedApiCall) | |
| { | |
| // Do stuff? | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment