一周前开始使用Ruby。编写API以连接RabbitMQ消息队列。添加新用户的命令行有效。
$ curl -i -u guest:guest -H“content-type:application / json”-XPUT -d'{“password”:“pwd”,“tags”:“administrator”}'{{3} }
我需要从Ruby发出这个Http Put请求。以下是我的代码: def test_add_user
uri = URI.parse('http://localhost:15672/api/users/karthik/')
uri.to_s
http = Net::HTTP.new(uri.host, uri.port)
request = Net::HTTP::Put.new(uri.path)
request.basic_auth 'guest', 'guest'
request['Content-Type'] = 'application/json'
request['Accept'] = 'application/json'
request.set_form_data({'password' => 'secret', 'tags' => 'management'})
http.start do |http|
res = http.request(request)
puts res
end
端
这是我得到的结果
o.test_add_user
#<Net::HTTPUnsupportedMediaType:0x007fd7fb6fe1d8>
=> nil
媒体类型异常与Content-Type有关吗? 仅允许application / json
我应该使用像to_json这样的东西吗?如果是,应该在哪里使用?提前谢谢。
此致 KARTHIK
答案 0 :(得分:2)
谢谢Hector和ptd。固定它。附上工作代码以供将来参考。
def test_add_user
uri = URI.parse('http://localhost:15672/api/users/Test1/')
http = Net::HTTP.new(uri.host, uri.port)
request = Net::HTTP::Put.new(uri.path)
request.basic_auth 'guest', 'guest'
request['Content-Type'] = 'application/json'
request['Accept'] = 'application/json'
request.body = {'password' => 'secret', 'tags' => 'management'}.to_json
http.start do |http|
res = http.request(request)
puts res
end
end
将新用户添加到RabbitMQ队列