【问题标题】:Sending a Post request with net/http使用 net/http 发送 Post 请求
【发布时间】:2013-06-14 08:24:54
【问题描述】:

我需要将 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'"):

【问题讨论】:

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


【解决方案1】:

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

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)

【讨论】:

  • 为什么不直接打电话给http.post(..? :) 这个method
  • 如何给http.post添加post参数?
  • @NathanB 知道这已经晚了 3 年多,但以防其他人有同样的问题,参数将传递到数据变量中。 data = {"whatever": array_or_hash, "password_param": "password"} 然后在目标站点上,您可以调用 params["whatever"] 或 params["password_param"] 来访问发送的数据。
猜你喜欢
  • 2016-08-04
  • 2022-08-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-14
  • 1970-01-01
  • 2023-03-22
相关资源
最近更新 更多