Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class WebClient
- {
- private static HttpClient httpClient;
- private static WebClient client;
- private WebClient()
- {
- httpClient = new HttpClient();
- httpClient.BaseAddress = new Uri(ConfigurationManager.AppSettings["JusticaGovPtServicosRCBE_ApiUrl"]);
- try
- {
- double connectionTimeout = 100.0;
- if (double.TryParse(ConfigurationManager.AppSettings["JusticaGovPtServicosRCBE_ApiTimeoutSecconds"], out connectionTimeout))
- {
- httpClient.Timeout = TimeSpan.FromSeconds(connectionTimeout);
- }
- }
- catch (Exception) { }
- httpClient.DefaultRequestHeaders.Accept.Clear();
- httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));
- }
- public static WebClient Create()
- {
- if (client == null)
- {
- client = new WebClient();
- }
- return client;
- }
- public Uri CreateURI(string path)
- {
- return new Uri(httpClient.BaseAddress.AbsoluteUri + path);
- }
- public T Get<T>(Uri uri)
- {
- return GetAsync<T>(uri).Result;
- }
- private async Task<T> GetAsync<T>(Uri uri)
- {
- T result = default(T);
- using (HttpResponseMessage response = await httpClient.GetAsync(uri).ConfigureAwait(false))
- {
- if (response.IsSuccessStatusCode)
- {
- result = await response.Content.ReadAsAsync<T>().ConfigureAwait(false);
- }
- return result;
- }
- }
- public TResult Post<TSource, TResult>(Uri uri, TSource source)
- {
- return PostAsync<TSource, TResult>(uri, source).Result;
- }
- private async Task<TResult> PostAsync<TSource, TResult>(Uri uri, TSource source)
- {
- TResult ret = default(TResult);
- using (HttpResponseMessage response = await httpClient.PostAsJsonAsync(uri, source).ConfigureAwait(false))
- {
- if (response.IsSuccessStatusCode)
- {
- ret = await response.Content.ReadAsAsync<TResult>().ConfigureAwait(false);
- }
- return ret;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement