Follow the leader
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This repo is archived. You can view files and clone it, but cannot push or open issues/pull-requests.

67 lines
2.5KB

  1. using System;
  2. using System.Net;
  3. using System.Text;
  4. using System.IO;
  5. using Newtonsoft.Json;
  6. namespace Leadercraft.Server
  7. {
  8. internal class LeadercraftApi
  9. {
  10. private readonly uint _userId;
  11. private readonly string _tokenUrl;
  12. private readonly string _criteriaUrl;
  13. public LeadercraftApi(uint userId, string tokenUrl, string criteriaUrl)
  14. {
  15. this._userId = userId;
  16. this._tokenUrl = tokenUrl;
  17. this._criteriaUrl = criteriaUrl;
  18. }
  19. public LeadercraftResult<KeyStruct> RequestPOSTToken()
  20. {
  21. NewKeyStruct reqBodyObj = new NewKeyStruct{ PlayerID = _userId };
  22. byte[] reqBodyBytes = Encoding.ASCII.GetBytes(JsonConvert.SerializeObject(reqBodyObj));
  23. // Request
  24. WebRequest request = WebRequest.Create(_tokenUrl);
  25. request.Method = "POST";
  26. request.ContentLength = reqBodyBytes.Length;
  27. request.ContentType = "application/json";
  28. Stream body = request.GetRequestStream();
  29. body.Write(reqBodyBytes, 0, reqBodyBytes.Length);
  30. body.Close();
  31. // Response
  32. HttpWebResponse response = (HttpWebResponse)request.GetResponse();
  33. body = response.GetResponseStream();
  34. byte[] respBodyBytes = new byte[int.Parse(response.GetResponseHeader("Content-Length"))];
  35. body.Read(respBodyBytes, 0, int.Parse(response.GetResponseHeader("Content-Length")));
  36. response.Close();
  37. return new LeadercraftResult<KeyStruct>(respBodyBytes, (int)response.StatusCode);
  38. }
  39. public LeadercraftResult<string> RequestPOSTCriteria(CriteriaStruct criteria, string token)
  40. {
  41. criteria.PlayerID = (int)_userId;
  42. byte[] reqBodyBytes = Encoding.ASCII.GetBytes(JsonConvert.SerializeObject(criteria));
  43. // Request
  44. WebRequest request = WebRequest.Create(_criteriaUrl);
  45. request.Method = "POST";
  46. request.ContentLength = reqBodyBytes.Length;
  47. request.ContentType = "application/json";
  48. request.Headers.Add(HttpRequestHeader.Authorization, "leadercraft "+token);
  49. Stream body = request.GetRequestStream();
  50. body.Write(reqBodyBytes, 0, reqBodyBytes.Length);
  51. body.Close();
  52. // Response
  53. HttpWebResponse response = (HttpWebResponse)request.GetResponse();
  54. body = response.GetResponseStream();
  55. byte[] respBodyBytes = new byte[int.Parse(response.GetResponseHeader("Content-Length"))];
  56. body.Read(respBodyBytes, 0, int.Parse(response.GetResponseHeader("Content-Length")));
  57. response.Close();
  58. return new LeadercraftResult<string>(respBodyBytes, (int)response.StatusCode);
  59. }
  60. }
  61. }