Advertisement
Guest User

Untitled

a guest
Aug 20th, 2019
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.45 KB | None | 0 0
  1. public class WebClient
  2. {
  3. private static HttpClient httpClient;
  4. private static WebClient client;
  5.  
  6. private WebClient()
  7. {
  8. httpClient = new HttpClient();
  9. httpClient.BaseAddress = new Uri(ConfigurationManager.AppSettings["JusticaGovPtServicosRCBE_ApiUrl"]);
  10. try
  11. {
  12. double connectionTimeout = 100.0;
  13. if (double.TryParse(ConfigurationManager.AppSettings["JusticaGovPtServicosRCBE_ApiTimeoutSecconds"], out connectionTimeout))
  14. {
  15. httpClient.Timeout = TimeSpan.FromSeconds(connectionTimeout);
  16. }
  17. }
  18. catch (Exception) { }
  19. httpClient.DefaultRequestHeaders.Accept.Clear();
  20. httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));
  21. }
  22.  
  23. public static WebClient Create()
  24. {
  25. if (client == null)
  26. {
  27. client = new WebClient();
  28. }
  29.  
  30. return client;
  31. }
  32.  
  33. public Uri CreateURI(string path)
  34. {
  35. return new Uri(httpClient.BaseAddress.AbsoluteUri + path);
  36. }
  37.  
  38. public T Get<T>(Uri uri)
  39. {
  40. return GetAsync<T>(uri).Result;
  41. }
  42.  
  43. private async Task<T> GetAsync<T>(Uri uri)
  44. {
  45. T result = default(T);
  46.  
  47. using (HttpResponseMessage response = await httpClient.GetAsync(uri).ConfigureAwait(false))
  48. {
  49. if (response.IsSuccessStatusCode)
  50. {
  51. result = await response.Content.ReadAsAsync<T>().ConfigureAwait(false);
  52. }
  53. return result;
  54. }
  55. }
  56.  
  57.  
  58. public TResult Post<TSource, TResult>(Uri uri, TSource source)
  59. {
  60. return PostAsync<TSource, TResult>(uri, source).Result;
  61. }
  62.  
  63.  
  64. private async Task<TResult> PostAsync<TSource, TResult>(Uri uri, TSource source)
  65. {
  66. TResult ret = default(TResult);
  67.  
  68. using (HttpResponseMessage response = await httpClient.PostAsJsonAsync(uri, source).ConfigureAwait(false))
  69. {
  70. if (response.IsSuccessStatusCode)
  71. {
  72. ret = await response.Content.ReadAsAsync<TResult>().ConfigureAwait(false);
  73. }
  74. return ret;
  75. }
  76. }
  77. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement