Posting Ruby data in JSON format with Net/http

99封情书 提交于 2019-12-12 09:03:33

问题


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

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?


回答1:


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)



回答2:


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


来源:https://stackoverflow.com/questions/29371622/posting-ruby-data-in-json-format-with-net-http

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