4

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?

1 Answer 1

18

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.

Sign up to request clarification or add additional context in comments.

2 Comments

When I send HTTP request to the server using: curl -v -H "Content-Type: application/json" -X GET -d "{"bbrequest":"BBTest","reqid":"44","data":{"name":"test"}}" localhost:8099 ... my server sees JSON data as "{bbrequest:BBTest,reqid:44,data:{name:test}}" When I send the request using the code you suggested, it sees it as "{\"bbrequest\":\"BBTest\",\"reqid\":\"44\",\"data\":{\"name\":\" test\"}}" and server is unable to parse it, perhaps there are some extra options I need to set to send request from ruby to exclude those extra characters? Can you please help. Thanks in advance.
That's because of converting the hash to json format. You will have to decode it. E.g. {"a"=>"b"}.to_json gives you "{\"a\":\"b\"}" and ActiveSupport::JSON.decode("{\"a\":\"b\"}") gives you {"a"=>"b"}.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.