http以JSON格式发布Ruby数据

http以JSON格式发布Ruby数据

本文介绍了使用Net/http以JSON格式发布Ruby数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个ruby文件:

I have this ruby file:

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数据而不先转换为哈希的方法吗?

which attempts to create a new account. However I get code: 400, invalid fields in account. I tested the data independently, so I'm (relatively) certain that the json itself isn't in an incorrect format; the problem is in trying to submit the data in the hash format that the post_Form requires. Does anyone know a way to use ruby to directly post json data without converting to a hash first?

推荐答案

制作请求对象,如下所示:

Make a request object like so:

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

这篇关于使用Net/http以JSON格式发布Ruby数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-21 01:20