public static TResult Post <TResult, TData>(HttpTargetType apiName, string apiMethod, string url, TData data, ContentType dataType = ContentType.Json, HeaderType headerType = HeaderType.Standard, int maxSecsToSendEmail = 30) where TResult : class { return(CallApi <TResult, TData>(apiName, apiMethod, url, data, headerType, maxSecsToSendEmail, (client, uri, content) => { switch (dataType) { case ContentType.Json: return client.PostAsync(uri, new StringContent(JsonConvert.SerializeObject(content), Encoding.UTF8, "application/json")); case ContentType.Xml: var stringWriter = new System.IO.StringWriter(); XmlWriter xmlWriter = XmlWriter.Create(stringWriter, new XmlWriterSettings() { OmitXmlDeclaration = true, Indent = true, ConformanceLevel = ConformanceLevel.Auto }); var serializer = new XmlSerializer(typeof(TData)); serializer.Serialize(xmlWriter, data); xmlWriter.Close(); return client.PostAsync(uri, new StringContent(stringWriter.ToString(), Encoding.UTF8, "application/xml")); } return null; })); }
public static TResult Get <TResult>(HttpTargetType apiName, string apiMethod, string url, HeaderType headerType = HeaderType.Standard, int maxSecsToSendEmail = 30) where TResult : class { return(CallApi <TResult, Object>(apiName, apiMethod, url, null, headerType, maxSecsToSendEmail, (client, uri, x) => { return client.GetAsync(uri); })); }
private static TResult CallApi <TResult, TData>(HttpTargetType apiName, string apiMethod, string url, TData data, HeaderType headerType, int maxSecsToSendEmail, Func <HttpClient, string, TData, Task <HttpResponseMessage> > asyncCall) where TResult : class { TResult result = null; string json = null; var entry = LogResults ? new HttpCallLogEntry(apiName, apiMethod, url, data, maxSecsToSendEmail) : null; try { if (url == null || url.Length < 10) { FscApplication.Current.FireAddLogEntry("ApiClient", "ApiClient url problem? Url(" + url + "), Stacktrace: " + Environment.StackTrace, true); } var async = asyncCall(GetClient(headerType), Uri.EscapeUriString(url), data); async.Wait(); var task = async.Result.Content.ReadAsStringAsync(); task.Wait(); json = task.Result; if (entry != null) { entry.End(json); } result = !string.IsNullOrEmpty(json) ? JsonConvert.DeserializeObject <TResult>(json) : null; } catch (Exception e) { if (entry != null) { entry.Exception(e); } throw e; } finally { entry?.Save(); } return(result); }