使用Net / http发布JSON格式的Ruby数据

时间:2015-03-31 14:51:45

标签: ruby json net-http

我有这个ruby文件:

require 'net/http'
require 'json'
require 'uri'
    #test data

newAcctJson ='{
  "type": "Credit Card",
  "nickname": "MoreTesting",
  "rewards": 2,
  "balance": 50
}'

    #creates a new account
def createAcct(custID, json)
    url = "http://api.reimaginebanking.com:80/customers/#{custID}/accounts?key=#{APIkey}"
    uri = URI.parse(url)
    http = Net::HTTP.new(uri.host, uri.port)
    myHash = JSON.parse(json)
    resp = Net::HTTP.post_form(uri, myHash)
    puts(resp.body)
end

尝试创建新帐户。但是我得到code: 400, invalid fields in account。我独立测试了数据,所以我(相对)确定json本身的格式不正确;问题在于尝试以post_Form所需的哈希格式提交数据。有没有人知道如何使用ruby直接发布json数据而不先转换为哈希?

2 个答案:

答案 0 :(得分:10)

创建一个请求对象:

request = Net::HTTP::Post.new(uri.request_uri, 
          'Content-Type' => 'application/json')
request.body = newAcctJson
resp = http.request(request)

答案 1 :(得分:3)

结合问题中的代码和@ DVG的优秀答案:

require 'net/http'
#require 'json' - not needed for the example
require 'uri'

#test data
newAcctJson ='{
  "type": "Credit Card",
  "nickname": "MoreTesting",
  "rewards": 2,
  "balance": 50
}'

#creates a new account
def createAcct(custID, json)
  url = "http://api.reimaginebanking.com:80/customers/#{custID}/accounts?key=#{APIkey}"
  uri = URI.parse(url)
  http = Net::HTTP.new(uri.host, uri.port)

  request = Net::HTTP::Post.new(
    uri.request_uri, 
    'Content-Type' => 'application/json'
  )
  request.body = newAcctJson

  response = http.request(request)
  puts(response.body)
end