Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending HTTP request using ruby on rails

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

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?

like image 592
Bilal Wahla Avatar asked Dec 03 '22 08:12

Bilal Wahla


1 Answers

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.

like image 92
David Avatar answered Dec 09 '22 16:12

David