Ruby-on-rails 使用 net/http 发送 Post 请求
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17163507/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sending a Post request with net/http
提问by Elmor
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 )
我需要将 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 }
But i get Net::HTTPBadResponse (wrong status line: "-ERR unknown command 'POST'"):How can i solve this problem?
但我得到Net::HTTPBadResponse (wrong status line: "-ERR unknown command 'POST'"):如何解决这个问题?
Update 1
Updated my code as @Raja-d suggested
更新 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
But i still get error Net::HTTPBadResponse (wrong status line: "-ERR unknown command 'POST'"):
但我仍然收到错误 Net::HTTPBadResponse (wrong status line: "-ERR unknown command 'POST'"):
回答by oldergod
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)

