18

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?

2 Answers 2

20

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.

4

Easiest way is with Net::HTTP:

require 'net/http'
http = Net::HTTP.new('www.data.com')
response = http.request_put('/?access_token=123', jsonbody)
1
  • 2
    i receive the error: /usr/lib/ruby/1.8/net/http.rb:1060:in request': undefined method closed?' for nil:NilClass (NoMethodError) from /usr/lib/ruby/1.8/net/http.rb:996:in `request_put' from json.rb:23
    – dpigera
    Commented Jan 21, 2011 at 19:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.