Ruby Http Post Parameters

2019-07-17 07:45发布

问题:

How can I add post parameters to what I have right now:

@toSend = {
        "nonce" => Time.now.to_i,
        "command" => "returnCompleteBalances"
    }.to_json    

uri = URI.parse("https://poloniex.com/tradingApi")
        https = Net::HTTP.new(uri.host,uri.port)
        https.use_ssl = true
        https.verify_mode = OpenSSL::SSL::VERIFY_NONE
        req = Net::HTTP::Post.new(uri.path, initheader = {'Content-Type' =>'application/json'})
        req.set_form_data({"nonce" => Time.now.to_i, "command" => "returnCompleteBalances"})
        req['Key'] = '******-N4WZI2OG-******-10RX5JYR'
        req['Sign'] = 'secret_key'

        req.body = "[ #{@toSend} ]"
        res = https.request(req)
        puts "Response #{res.code} #{res.message}: #{res.body}"

These are the params I want to send:

"nonce" => Time.now.to_i,
"command" => "returnCompleteBalances"

Thank you.

回答1:

It appears that you're trying to use Poloniex's trading API. If this is your primary goal, you might wish to consider using a library to handle the nitty-gritty details. For example:

https://github.com/Lowest0ne/poloniex

If your primary goal is not simply to use the API, but to use this as a learning experience, here are a few pointers:

  • The API documentation indicates that the API accepts form-encoded POST data (not JSON) but responds with JSON.
  • The key parameter ("Key") is like your user id. It allows Poloniex to understand who is attempting to make a request against the API.
  • The signature parameter ("Sign") is an HMAC generated from the contents of your secret key and the contents of your message (the encoded form data). This produces a sort of fingerprint that only you and Poloniex have the information to reproduce, giving some level of assurance that your request originated from the owner of the secret key. Of course, this assumes that your secret key is indeed only known by you.

I don't use the Poloniex exchange and cannot test this code, but I believe this is close to what you're attempting to accomplish:

require 'net/http'
require 'openssl'

secret = 'your-secret-key'
api_key = 'your-api-key'
uri = URI('https://poloniex.com/tradingApi')

http = Net::HTTP.new(uri.host)
request = Net::HTTP::Post.new(uri.request_uri)
form_data = URI.encode_www_form({:command => 'returnBalances', :nonce => Time.now.to_i * 1000 })
request.body = form_data
request.add_field('Key', api_key)
request.add_field('Sign', OpenSSL::HMAC.hexdigest( 'sha512', secret, form_data))

res = http.request(request)
puts res.body