Skip to content

Commit

Permalink
Merge pull request #10 from daniel-dressler/feature/jsonrpc
Browse files Browse the repository at this point in the history
Add JSON RPC
  • Loading branch information
Ron Korving committed Aug 18, 2015
2 parents 77cebca + 6f587c0 commit 1bf1c29
Showing 1 changed file with 67 additions and 0 deletions.
67 changes: 67 additions & 0 deletions JSONRPC/JSONRPC.cs
Original file line number Diff line number Diff line change
@@ -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<string, string> headers, Action<Exception, JObject> 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<string, string> _headers = new Dictionary<string, string>(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);
});
}
}

0 comments on commit 1bf1c29

Please sign in to comment.