Ruby: PUT Request with JSON body?

牧云@^-^@ 提交于 2019-12-03 07:04:54

问题


I need to create an HTTP PUT request using ruby.

The request has a JSON body

I was able to generate the JSON body using:

require 'rubygems'
require 'json'
jsonbody = JSON.generate["message"=>"test","user"=>"user1"]

I need to send this PUT request to the url:

require 'open-uri'
url = URI.parse('http://www.data.com?access_token=123')

Can someone please tell me how I can do this in Ruby?


回答1:


Using restclient (gem install rest-client) like this:

require 'rubygems'
require 'rest_client'
require 'json'

jdata = JSON.generate(["test"])
RestClient.put 'http://localhost:4567/users/123', jdata, {:content_type => :json}

against the following sinatra service:

require 'sinatra'
require 'json'

put '/users/:id' do |n|
  data = JSON.parse(request.body.read)
  "Got #{data} for user #{n}"
end

works on my computer.




回答2:


Easiest way is with Net::HTTP:

require 'net/http'
http = Net::HTTP.new('www.data.com')
response = http.request_put('/?access_token=123', jsonbody)


来源:https://stackoverflow.com/questions/4762541/ruby-put-request-with-json-body

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