HttpClient.cs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Net.Http;
  4. using System.Threading.Tasks;
  5. using VeloeKemonoPartyApp.Data;
  6. using System.Text.Json;
  7. namespace VeloeKemonoPartyApp.Services
  8. {
  9. public class KemonoHttpClient
  10. {
  11. public HttpClient httpClient;
  12. public List<Post> posts;
  13. public KemonoHttpClient()
  14. {
  15. httpClient = new HttpClient()
  16. {
  17. BaseAddress = new Uri("https://kemono.party")
  18. };
  19. posts = new List<Post>();
  20. }
  21. public async Task<List<Creator>> GetCreatorsList()
  22. {
  23. using (HttpResponseMessage response = await httpClient.GetAsync("https://kemono.party/api/creators"))
  24. using (HttpContent content = response.Content)
  25. {
  26. string jsonString = await response.Content.ReadAsStringAsync();
  27. Preferences.Set("creators", jsonString);
  28. // ... Read the string.
  29. return JsonSerializer.Deserialize<List<Creator>>(jsonString);
  30. }
  31. }
  32. public async Task<List<Post>> GetPostsList(string id, string service, int start)
  33. {
  34. using (HttpResponseMessage response = await httpClient.GetAsync($"https://kemono.party/api/{service}/user/{id}?o={start}"))
  35. using (HttpContent content = response.Content)
  36. {
  37. string jsonString = await response.Content.ReadAsStringAsync();
  38. // ... Read the string.
  39. return JsonSerializer.Deserialize<List<Post>>(jsonString);
  40. }
  41. }
  42. public async Task GetImageAsync(string link, string toFolder, string toImage)
  43. {
  44. try
  45. {
  46. using (var s = await httpClient.GetStreamAsync(link))
  47. {
  48. if (!Directory.Exists(toFolder))
  49. Directory.CreateDirectory(toFolder);
  50. using (var fs = new FileStream(toImage, FileMode.CreateNew))
  51. {
  52. await s.CopyToAsync(fs);
  53. }
  54. }
  55. }
  56. catch (Exception)
  57. {
  58. System.IO.File.Delete(toImage);
  59. throw;
  60. }
  61. }
  62. }
  63. }