2

I am trying to pass a json representation to a set_form_data and am running into following error:

undefined method `map' for "{\"first_name\":\"bill\",\"last_name\":\"gates\"}":String

Here is how I create the request:

 Net::HTTP::Post.new(uri.request_uri).set_form_data({"first_name" => "steve","last_name" => "jobs"}.to_json)

Anything I am missing ?

The error comes from the line:

/jruby/jruby-1.6.2/lib/ruby/1.9/net/http.rb:1593:in `set_form_data'
codeObserver
  • 6,521
  • 16
  • 76
  • 121

2 Answers2

4

I used request.body=form_data instead of request.set_form_data and that worked.
However I dont know for sure why set_form_data did not work.

Marking this as an answer, since that's the one that worked for me so far.

Nakilon
  • 34,866
  • 14
  • 107
  • 142
codeObserver
  • 6,521
  • 16
  • 76
  • 121
2

set_form_data wants a hash, not a json, so skip the to_json and it should work better.

ie:

some_data = {:foo => :bar, :meh => :muh}
Net::HTTP::Post.new(uri.request_uri).set_form_data(some_data)
scones
  • 3,317
  • 23
  • 34
  • Thanks scones for the comments. If I skip the to_json, I get the following error: ["{\"message\":\"Invalid JSON\"}", "400"] ["{\"message\":\"Invalid JSON\"}", "400"] – codeObserver Apr 03 '13 at 07:05
  • @codeObserver you might want to take a look at this question (and answer) http://stackoverflow.com/questions/2024805/ruby-send-json-request basically everything you do with solutions – scones Apr 03 '13 at 07:15
  • @codeObserver I forgot the explanation, my bad: the first error you posted was from the gem function set_form_data, which complained about the wrong data type. the second error message you posted was the remote side complaning about wrong data type. this means that the first error was resolved and the remote side now produces a problem. you can solve this problem using the link provided. :) – scones Apr 03 '13 at 07:18
  • Thanks for the link and the explanaiton. I used to_json and request.body=form_data instead of request.set_form_data and that worked ! . However I am still confused what just happened :) – codeObserver Apr 03 '13 at 07:32