将 cURL 请求转换为 Ruby post 请求

Converting a cURL request to a Ruby post request

我正在尝试将我之前做过的快速 cURL hack 转换为 Ruby 等价物。即将结束。

我正在从

JSON API 打开的文件下载数据
http://api.turfgame.com/v4/users

使用以下 cURL 命令

curl -s -X POST -H "Content-Type: application/json" -d '[{"name": "tbone"}]' api.turfgame.com/v4/users

我的微弱尝试失败了。到目前为止我没有用的是

require 'net/http'
require 'rubygems'
require 'json'
require 'uri'

url = "http://api.turfgame.com/v4/users"
uri = URI.parse(url)
data = {"name" => "tbone"}

headers = {"Content-Type" => "application/json"}

http = Net::HTTP.new(uri.host,uri.port)

response = http.post(uri.path,data.to_json,headers)
    puts response.code
    puts response.body

我收到的错误消息是

400
{"errorMessage":"Invalid JSON string","errorCode":195887105}

我猜我没有正确发送请求,但如何发送?

欢迎指点!谢谢

您的 curl 请求包含此内容 [{"name": "tbone"}](内部包含哈希的数组),但在您的 Ruby 版本中,您只需发送没有包装数组的哈希 {"name" => "tbone"}

将您的 data 更改为:

data = [{"name" => "tbone"}]