当前位置 : 主页 > 网页制作 > HTTP/TCP >

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

来源:互联网 收集:自由互联 发布时间:2021-06-16
我有这个 ruby文件: require 'net/http'require 'json'require 'uri' #test datanewAcctJson ='{ "type": "Credit Card", "nickname": "MoreTesting", "rewards": 2, "balance": 50}' #creates a new accountdef createAcct(custID, json) url = "htt
我有这个 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

试图创建一个新帐户.但是我得到代码:400,帐户中的字段无效.我独立测试了数据,所以我(相对)确定json本身的格式不正确;问题在于尝试以post_Form所需的散列格式提交数据.有没有人知道如何使用ruby直接发布json数据而不首先转换为哈希?

像这样创建一个请求对象:

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