Sending a Post request with net/http

Elmor picture Elmor · Jun 18, 2013 · Viewed 33.7k times · Source

I need to send data in JSON to another app which runs on the same computer.
I send request like so (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 }

But i get Net::HTTPBadResponse (wrong status line: "-ERR unknown command 'POST'"): How can i solve this problem?

Update 1
Updated my code as @Raja-d suggested

  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

But i still get error Net::HTTPBadResponse (wrong status line: "-ERR unknown command 'POST'"):

Answer

oldergod picture oldergod · Jun 18, 2013

I don't know what your problem is but what about something like this

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)