Development

如何使用 C# 呼叫 JSON RPC API?

  • July 23, 2016

如何訪問 C# 中的 JSON RPC API,以便我還可以讀取介面提供的錯誤?

我使用Newtonsoft.Json.Linq如下所示的庫來獲取數據。很快,我將在http://www.coinapi.net上發布強類型 C# 客戶端庫

獲取 JSON 錯誤程式碼的主要技巧是在 catch 方法中再次呼叫 GetWebResponse()。然後返回並解析數據。我曾討論過在返回程式碼中包含 WebException 本身,但這可能需要進行太多更改。如果有人有想法,我很樂意接受。

       var ret = InvokeMethod("getblockhash", index);

這是 InvokeMethod 的定義

   public JObject InvokeMethod(string a_sMethod, params object[] a_params)
   {
       HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(Url);
       webRequest.Credentials = Credentials;

       webRequest.ContentType = "application/json-rpc";
       webRequest.Method = "POST";

       JObject joe = new JObject();
       joe["jsonrpc"] = "1.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));
           }
       }

       string s = JsonConvert.SerializeObject(joe);
       // serialize json for the request
       byte[] byteArray = Encoding.UTF8.GetBytes(s);
       webRequest.ContentLength = byteArray.Length;

       try
       {
           using (Stream dataStream = webRequest.GetRequestStream())
           {
               dataStream.Write(byteArray, 0, byteArray.Length);
           }
       }
       catch (WebException we)
       {
           //inner exception is socket
           //{"A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 23.23.246.5:8332"}
           throw;
       }
       WebResponse webResponse = null;
       try
       {
           using (webResponse = webRequest.GetResponse())
           {
               using (Stream str = webResponse.GetResponseStream())
               {
                   using (StreamReader sr = new StreamReader(str))
                   {
                       return JsonConvert.DeserializeObject<JObject>(sr.ReadToEnd());
                   }
               }
           }
       }
       catch (WebException webex)
       {

           using (Stream str = webex.Response.GetResponseStream())
           {
               using (StreamReader sr = new StreamReader(str))
               {
                   var tempRet =  JsonConvert.DeserializeObject<JObject>(sr.ReadToEnd());
                   return tempRet;
               }
           }

       } 
       catch (Exception)
       {

           throw;
       }
   }

引用自:https://bitcoin.stackexchange.com/questions/5810