Posting Ruby data in JSON format with Net/http

こ雲淡風輕ζ 提交于 2019-12-04 13:13:04
DVG

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)
Benjineer

To combine the code from the question and @DVG's excellent answer:

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
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!