使用 ruby​​ on Rails 发送 HTTP 请求

2023-12-30

我是 ruby​​ on Rails 的新手,并尝试测试我是否可以从我的控制器执行如下操作:

curl -v -H "Content-Type: application/json" -X GET -d "{bbrequest:BBTest reqid:44  data:{name: "test"}}" http://localhost:8099

在 HTTP 请求中发送 JSON 的最佳实践是什么?


你可以这样做:

def post_test
  require 'net/http'
  require 'json'

  @host = 'localhost'
  @port = '8099'

  @path = "/posts"

  @body ={
    "bbrequest" => "BBTest",
    "reqid" => "44",
    "data" => {"name" => "test"}
  }.to_json

  request = Net::HTTP::Post.new(@path, initheader = {'Content-Type' =>'application/json'})
  request.body = @body
  response = Net::HTTP.new(@host, @port).start {|http| http.request(request) }
  puts "Response #{response.code} #{response.message}: #{response.body}"
end

Look up 网络::HTTP http://www.rubyinside.com/nethttp-cheat-sheet-2940.html了解更多信息。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 ruby​​ on Rails 发送 HTTP 请求 的相关文章

随机推荐