Skip to content

Instantly share code, notes, and snippets.

@ElectricCoffee
Created February 3, 2014 21:48
Show Gist options
  • Save ElectricCoffee/8793123 to your computer and use it in GitHub Desktop.
Save ElectricCoffee/8793123 to your computer and use it in GitHub Desktop.
// credit for this goes to makerofthings7 on stack exchange
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Net;
using System.Web;
using System.IO;
namespace JsonRPC
{
class Program
{
static void Main(string[] args)
{
}
public JObject InvokeMethod(string url, string a_sMethod, params object[] a_params)
{
var webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.ContentType = "application/json-rpc";
webRequest.Method = "POST";
var joe = new JObject();
joe["jsonrpc"] = "2.0";
joe["id"] = "1";
joe["method"] = a_sMethod;
if (a_params != null)
{
if (a_params.Length > 0)
{
JArray props = new JArray();
foreach (var p in a_params)
{
props.Add(p);
}
joe.Add(new JProperty("params", props));
}
}
var s = JsonConvert.SerializeObject(joe);
// serialise json for the request
var byteArray = Encoding.UTF8.GetBytes(s);
webRequest.ContentLength = byteArray.Length;
try
{
using (var dataStream = webRequest.GetRequestStream())
{
dataStream.Write(byteArray, 0, byteArray.Length);
}
}
catch (WebException we)
{
Console.WriteLine(we.StackTrace);
}
WebResponse webResponse = null;
try
{
using (webResponse = webRequest.GetResponse())
{
using (var str = webResponse.GetResponseStream())
{
using (var sr = new StreamReader(str))
{
return JsonConvert.DeserializeObject<JObject>(sr.ReadToEnd());
}
}
}
}
catch (WebException we)
{
using (var str = we.Response.GetResponseStream())
{
using (var sr = new StreamReader(str))
{
return JsonConvert.DeserializeObject<JObject>(sr.ReadToEnd());
}
}
}
catch (Exception)
{
throw;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment