using System; using System.Net; using System.Text; using System.IO; using Newtonsoft.Json; namespace Leadercraft.Server { internal class LeadercraftApi { private readonly uint _userId; private readonly string _tokenUrl; private readonly string _criteriaUrl; public LeadercraftApi(uint userId, string tokenUrl, string criteriaUrl) { this._userId = userId; this._tokenUrl = tokenUrl; this._criteriaUrl = criteriaUrl; } public LeadercraftResult RequestPOSTToken() { NewKeyStruct reqBodyObj = new NewKeyStruct{ PlayerID = _userId }; byte[] reqBodyBytes = Encoding.ASCII.GetBytes(JsonConvert.SerializeObject(reqBodyObj)); // Request WebRequest request = WebRequest.Create(_tokenUrl); request.Method = "POST"; request.ContentLength = reqBodyBytes.Length; request.ContentType = "application/json"; Stream body = request.GetRequestStream(); body.Write(reqBodyBytes, 0, reqBodyBytes.Length); body.Close(); // Response HttpWebResponse response = (HttpWebResponse)request.GetResponse(); body = response.GetResponseStream(); byte[] respBodyBytes = new byte[int.Parse(response.GetResponseHeader("Content-Length"))]; body.Read(respBodyBytes, 0, int.Parse(response.GetResponseHeader("Content-Length"))); response.Close(); return new LeadercraftResult(respBodyBytes, (int)response.StatusCode); } public LeadercraftResult RequestPOSTCriteria(CriteriaStruct criteria, string token) { criteria.PlayerID = (int)_userId; byte[] reqBodyBytes = Encoding.ASCII.GetBytes(JsonConvert.SerializeObject(criteria)); // Request WebRequest request = WebRequest.Create(_criteriaUrl); request.Method = "POST"; request.ContentLength = reqBodyBytes.Length; request.ContentType = "application/json"; request.Headers.Add(HttpRequestHeader.Authorization, "leadercraft "+token); Stream body = request.GetRequestStream(); body.Write(reqBodyBytes, 0, reqBodyBytes.Length); body.Close(); // Response HttpWebResponse response = (HttpWebResponse)request.GetResponse(); body = response.GetResponseStream(); byte[] respBodyBytes = new byte[int.Parse(response.GetResponseHeader("Content-Length"))]; body.Read(respBodyBytes, 0, int.Parse(response.GetResponseHeader("Content-Length"))); response.Close(); return new LeadercraftResult(respBodyBytes, (int)response.StatusCode); } } }