带参数的Bitstamp API POST请求

时间:2017-10-17 15:47:58

标签: c# api

请帮我解决C#中的POST api请求。我不知道如何在POST请求中正确发送参数“key”,“signature”和“nonce”。它经常告诉我"缺少键,签名和随机数参数“。

HttpWebRequest webRequest =(HttpWebRequest)System.Net.WebRequest.Create("https://www.bitstamp.net/api/balance/");
   if (webRequest != null)
   {
       webRequest.Method = HttpMethod.Post;
       webRequest.ContentType = "application/json";
       webRequest.UserAgent = "BitstampBot";
       byte[] data = Convert.FromBase64String(apisecret);
       string nonce = GetNonce().ToString();
       var prehash = nonce + custID + apikey;
       string signature = HashString(prehash, data);
       body = Serialize(new
       {
           key=apikey,
           signature=signature,
           nonce=nonce
       });

       if (!string.IsNullOrEmpty(body))
       {
           var data1 = Encoding.UTF8.GetBytes(body);
           webRequest.ContentLength = data1.Length;
           using (var stream = webRequest.GetRequestStream()) stream.Write(data1, 0, data1.Length);
       }
       using (Stream s = webRequest.GetResponse().GetResponseStream())
       {
           using (StreamReader sr = new System.IO.StreamReader(s))
           {
               contentBody = await sr.ReadToEndAsync();
                   return contentBody;
           }
       }
   }

1 个答案:

答案 0 :(得分:1)

"请求参数"正如在docs中指定的Bitstamp实际上应该与内容类型" application / x-www-form-urlencoded"而不是" application / json"。

我还会使用HttpClient来执行帖子,因为它有一个更简单的设置来执行Http请求

using (var client = new HttpClient())
{
    var content = new FormUrlEncodedContent(new[]
    {
        new KeyValuePair<string, string>("key", apikey),
        new KeyValuePair<string, string>("signature", signature),
        new KeyValuePair<string, string>("nonce", nonce)
    });
    var result = await client.PostAsync("https://www.bitstamp.net/api/balance/", content);
    string resultContent = await result.Content.ReadAsStringAsync();
}