有没有办法在Ruby中使用Net::HTTP传递参数和headers?

Is there a way to pass parameters and headers using Net::HTTP in Ruby?

我正在尝试构建一个小 Ruby 脚本来与 Binance API (https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md)

进行交互

这是我目前所拥有的。这是一个脚本,但为了清楚起见,我将其分为 "what I think works" 和 "what I think is broken" 部分:

我认为包含、函数和参数创建工作正常:

require 'json'
require 'uri'
require 'net/http'
require 'openssl'

def params_with_signature(params, secret)
  params = params.reject { |_k, v| v.nil? }
  query_string = URI.encode_www_form(params)
  signature = OpenSSL::HMAC.hexdigest(OpenSSL::Digest.new('sha256'), secret, query_string)
  params = params.merge(signature: signature)
end

BASE_URL = 'https://api.binance.com'
api_key = ''
api_secret = ''

params = {
    symbol: 'BNBBTC',
    side: 'BUY',
    type: 'MARKET',
    timeInForce: 'GTC',
    quantity: 1,
    recvWindow: 5000,
    timestamp: Time.now.to_i * 1000
}

我认为这是问题所在

uri = URI("#{BASE_URL}/api/v3/order")

header = {'Content-Type': 'text/json'}

http = Net::HTTP.new(uri.host, uri.port)
request = Net::HTTP::Post.new(uri.request_uri, header)
request.body = params_with_signature(params, api_secret).to_json
request["X-MBX-APIKEY"] = api_key

response = http.request(request)

puts response.body

问题是我在尝试发送请求时不断收到各种 "malformed" 错误。同样,我认为问题在于上面的 Net::HTTP post 尝试。

任何想法都会很棒!

我不确定它是否适合您,但我已经重写了您的代码以使用 HTTParty gem 而不是 net/http。在我看来,使用这个 gem 更容易。 结果,我得到了 {"code":-2014,"msg":"API-key format invalid."},我认为这是一个正确的回应,因为我没有 Binance 的 API 密钥。

require 'json'
require 'uri'
require 'httparty'
require 'openssl'

def params_with_signature(params, secret)
  params = params.reject { |_k, v| v.nil? }
  query_string = URI.encode_www_form(params)
  signature = OpenSSL::HMAC.hexdigest(OpenSSL::Digest.new('sha256'), secret, query_string)
  params.merge(signature: signature)
end

params = {
    symbol: 'BNBBTC',
    side: 'BUY',
    type: 'MARKET',
    timeInForce: 'GTC',
    quantity: 1,
    recvWindow: 5000,
    timestamp: Time.now.to_i * 1000
}

BASE_URL = 'https://api.binance.com'
api_key = ''
api_secret = ''

uri = URI("#{BASE_URL}/api/v3/order")

headers = {
  'X-MBX-APIKEY': api_key,
  'Content-Type': 'text/json'
}

response = HTTParty.post(uri, headers: headers, body: params_with_signature(params, api_secret))

puts response.body

如果对您有帮助,请告诉我:)

对于 Net/Http 的解决方案,您可以在这里查看: