-
Notifications
You must be signed in to change notification settings - Fork 13
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #10 from daniel-dressler/feature/jsonrpc
Add JSON RPC
- Loading branch information
Showing
1 changed file
with
67 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
}); | ||
} | ||
} |