diff --git a/JSONRPC/JSONRPC.cs b/JSONRPC/JSONRPC.cs new file mode 100755 index 0000000..0cb6d9f --- /dev/null +++ b/JSONRPC/JSONRPC.cs @@ -0,0 +1,67 @@ +using System; +using System.Collections.Generic; +using System.Net; +using System.IO; +using System.Text; + +using Newtonsoft.Json.Linq; + +public class JSONRPC { + private string _endpoint; + + // Basic authentication + private string _username; + private string _password; + + public void setEndpoint(string endpoint, string username = null, string password = null) { + _endpoint = endpoint; + _username = username; + _password = password; + } + + public void call(string methodName, JObject parameters, Dictionary headers, Action cb) { + // Make sure the endpoint is set + if (string.IsNullOrEmpty(_endpoint)) { + cb(new Exception("Endpoint has not been set"), null); + return; + } + + // Setup JSON request object + JObject requestObject = new JObject (); + requestObject.Add("id", new JValue(1)); + requestObject.Add("jsonrpc", new JValue("2.0")); + requestObject.Add("method", new JValue(methodName)); + requestObject.Add("params", parameters); + + // Serialize JSON request object into string + string postData; + try { + postData = requestObject.ToString (); + } catch (Exception serializeError) { + cb(serializeError, null); + return; + } + + // Make a copy of the provided headers and add additional required headers + Dictionary _headers = new Dictionary(headers); + if (_username != null && _password != null) { + string authInfo = _username + ":" + _password; + string encodedAuth = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo)); + _headers.Add("Authorization", "Basic " + encodedAuth); + } + + // Send HTTP post to JSON rpc endpoint + HTTPRequest.Post (_endpoint, "application/json", postData, _headers, (Exception requestError, string responseString) => { + // Deserialize the JSON response + JObject responseObject; + try { + responseObject = JObject.Parse(responseString); + } catch (Exception error) { + cb(error, null); + return; + } + + cb(null, responseObject); + }); + } +}