在 ruby 中将 curl 转换为 open-uri?

Transform curl to open-uri in ruby?

我有这样的卷曲线:

curl https://api.paymill.com/v2.1/checksums -u 'private_user_key' -d 'checksum_type=paypal' -d 'amount=4200'

我想将其转换为这样的 open-uri 调用:

require 'open-uri'
open("https://api.paymill.com/v2.1/checksums", http_basic_authentication: ['private_user_key'])

目前有效,但我如何包含 -d 数据属性,如 -d 'checksum_type=paypal' -d 'amount=4200'?

谢谢,安德烈亚斯

我认为你最好直接使用 Net::HTTP(而不是 open-uri,它只是一个方便的包装器)。这使您可以更好地控制发出的请求。

require 'net/http'
uri = URI("https://api.paymill.com/v2.1/checksums")
http = Net::HTTP.new(uri.host, uri.port)
request = Net::HTTP::Post.new(uri.request_uri)
request.basic_auth("username", "password")
request.set_form_data('checksum_type' => 'paypal', 'amount' => 4200)
response = http.request(request)

我在此处找到了一些非常好的 Net::HTTP 示例,包括表单请求:http://www.rubyinside.com/nethttp-cheat-sheet-2940.html