在rails上使用ruby发送HTTP请求

时间:2021-07-28 07:34:46

I'm new to ruby on rails and trying to simply test if I could simply do something like the below from my controller:

我是ruby on rails的新手,试图简单地测试我是否可以从我的控制器中执行以下操作:

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

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

And what is the best practice to send JSON in your HTTP requests?

在HTTP请求中发送JSON的最佳做法是什么?

Thanks

1 个解决方案

#1


17  

You could do something like this:

你可以这样做:

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 Net::HTTP for more information.

查找Net :: HTTP以获取更多信息。

#1


17  

You could do something like this:

你可以这样做:

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 Net::HTTP for more information.

查找Net :: HTTP以获取更多信息。