sharp-jsonrpc/RPCConnector.cs

54 lines
1.3 KiB
C#
Raw Normal View History

2017-09-18 11:30:23 +02:00
using System;
using System.Net.Http;
using System.Threading.Tasks;
using System.Collections.Generic;
2017-10-17 21:43:50 +02:00
namespace sharp.jsonrpc
2017-09-18 11:30:23 +02:00
{
public class RPCConnector
{
private readonly HttpClient http;
public RPCConnector(string hostname,int port)
{
this.http = new HttpClient();
this.Hostname = hostname;
this.Port = port;
}
public String Hostname { get; private set; }
public int Port { get; private set; }
public string URL { get { return String.Format("http://{0}:{1}/json_rpc",Hostname,Port); } }
public RPCCall Call(){
return new RPCCall(this);
}
public Response Call(string method)
{
return Call(method, null);
}
public Response Call(string method,Dictionary<String,object> args){
try
{
2017-10-17 21:43:50 +02:00
string request = sharp.jsonrpc.Request.Create(method,args);
//Console.WriteLine("json-call: {0}",request);
2017-09-18 11:30:23 +02:00
Task<HttpResponseMessage> response = http.PostAsync(URL, new StringContent(request));
response.Wait();
Task<string> result = response.Result.Content.ReadAsStringAsync();
result.Wait();
return new Response(result.Result);
}
catch (HttpRequestException e)
{
2017-10-17 21:43:50 +02:00
Response resp = new Response(String.Format("{ \"id\": \"0\", \"sharp.jsonrpc\": \"2.0\", \"result\": { status: \"Error\", message: \"HttpException: {0}\"}", e.ToString()));
2017-09-18 11:30:23 +02:00
return resp;
}
}
}
}