RestApiRequester.cs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. using System;
  2. using System.Net.Http;
  3. using System.Text;
  4. using System.Text.Json;
  5. using System.Threading.Tasks;
  6. namespace gameapi.Library
  7. {
  8. public class RestApiRequester
  9. {
  10. public async Task<dynamic> GetJson(string url)
  11. {
  12. var contentString = string.Empty;
  13. var client = new HttpClient();
  14. try
  15. {
  16. var response = await client.GetAsync(url);
  17. contentString = await response.Content.ReadAsStringAsync();
  18. return JsonSerializer.Deserialize<dynamic>(contentString);
  19. }
  20. catch (Exception e)
  21. {
  22. Console.WriteLine("Issue with making the curl; I tried " + url);
  23. Console.WriteLine(e.Message);
  24. contentString = $"Something went wrong: {e.Message}";
  25. }
  26. return contentString;
  27. }
  28. public async Task<dynamic> GetString(string url)
  29. {
  30. var client = new HttpClient();
  31. try
  32. {
  33. var response = await client.GetAsync(url);
  34. return await response.Content.ReadAsStringAsync();
  35. }
  36. catch (Exception e)
  37. {
  38. Console.WriteLine($"Issue with making the curl; I tried '{url}'.");
  39. Console.WriteLine(e.Message);
  40. return $"Something went wrong: {e.Message}";
  41. }
  42. }
  43. public async Task PostJson(string url, dynamic data)
  44. {
  45. var client = new HttpClient();
  46. try
  47. {
  48. var content = new StringContent(JsonSerializer.Serialize(data), Encoding.UTF8, "application/json");
  49. await client.PostAsync(url, content);
  50. }
  51. catch (Exception e)
  52. {
  53. Console.WriteLine($"Issue with making the post; I tried '{url}'.");
  54. Console.WriteLine(e.Message);
  55. }
  56. }
  57. }
  58. }