using System; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using ln.json; using ln.logging; namespace ln.build { public class JsonApiClient : IDisposable { public string BaseURL { get; } public HttpClient HttpClient { get; } public JsonApiClient(string baseUrl) { HttpClient = new HttpClient(); BaseURL = baseUrl; } public HttpStatusCode GetJson(out JSONValue response,params string[] path) { HttpResponseMessage httpResponse = HttpClient.GetAsync(string.Format("{0}/{1}",BaseURL, string.Join('/', path))).Result; if (httpResponse.StatusCode == System.Net.HttpStatusCode.OK) { response = JSONParser.Parse(httpResponse.Content.ReadAsStringAsync().Result); } else { response = null; } return httpResponse.StatusCode; } public HttpStatusCode PostJson(JSONValue content, out JSONValue response,params string[] path) { StringContent jsonContent = new StringContent(content.ToString(),Encoding.UTF8, "application/json"); HttpResponseMessage httpResponse = HttpClient.PostAsync(string.Format("{0}/{1}",BaseURL, string.Join('/', path)),jsonContent).Result; if (httpResponse.StatusCode == System.Net.HttpStatusCode.Created) { response = JSONParser.Parse(httpResponse.Content.ReadAsStringAsync().Result); } else { response = null; Logging.Log(LogLevel.DEBUG, "failed URL: {0}", httpResponse.RequestMessage.RequestUri); Logging.Log(LogLevel.DEBUG, "httpResponse; {0}", httpResponse); } return httpResponse.StatusCode; } public HttpStatusCode PostContent(HttpContent content, out JSONValue response,params string[] path) { HttpResponseMessage httpResponse = HttpClient.PostAsync(string.Format("{0}/{1}",BaseURL, string.Join('/', path)),content).Result; if (httpResponse.StatusCode == System.Net.HttpStatusCode.Created) { response = JSONParser.Parse(httpResponse.Content.ReadAsStringAsync().Result); } else { response = null; Logging.Log(LogLevel.DEBUG, "failed URL: {0}", httpResponse.RequestMessage.RequestUri); Logging.Log(LogLevel.DEBUG, "httpResponse; {0}", httpResponse); } return httpResponse.StatusCode; } public HttpStatusCode Delete(params string[] path) => HttpClient.DeleteAsync(string.Format("{0}/{1}",BaseURL, string.Join('/', path))).Result.StatusCode; public void Dispose() { HttpClient?.Dispose(); } static JsonApiClient(){ System.Net.ServicePointManager.Expect100Continue = false; } } }