使用net / http发送Post请求

时间:2013-06-18 08:00:08

标签: ruby-on-rails ruby json post net-http

我需要将JSON中的数据发送到另一个在同一台计算机上运行的应用程序 我这样发送请求(rails 3.2.13)

 data = { //some data hash }
 url = URI.parse('http://localhost:6379/api/plans')
  resp, data = Net::HTTP.post_form(url, data.to_JSON )
  p resp
  p data
  { resp: resp, data: data.to_JSON }

但我得Net::HTTPBadResponse (wrong status line: "-ERR unknown command 'POST'"): 我怎么解决这个问题?

更新1
将我的代码更新为@ Raja-d建议

  url = URI.parse('http://localhost:6379/v1/sessions')
  http = Net::HTTP.new(url.host, url.port)
  http.use_ssl = true
  resp, data = Net::HTTP.post_form(url, data)
  p resp
  p data

但我仍然收到错误Net::HTTPBadResponse (wrong status line: "-ERR unknown command 'POST'"):

1 个答案:

答案 0 :(得分:40)

我不知道你的问题是什么,但是这样的事情

http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true

request = Net::HTTP::Post.new(uri.path, {'Content-Type' => 'application/json'})
request.body = data.to_json

response = http.request(request)