Reputation: 197
I am trying to write a simple http post which will send a json body to a restful api. I am using the following code:
data = {'EmailAddress' => email, 'Name' => 'bobby', 'CustomFields' => [ {'Key' => 'Country', 'Value' => 'canada'}, {'Key' => 'City', 'Value' => 'vancouver'} ], 'Resubscribe' => true }.to_json
require 'net/http'
net = Net::HTTP.new("api.createsend.com", 80)
request = Net::HTTP::Post.new("/api/v3/subscribers/#{@list}.json")
request.basic_auth(@api, 'magic')
request.set_form_data(:body => data)
response = net.start do |http|
http.request(request)
end
puts response.code
puts response.read_body
The trouble I am having is the body is going to the server as a string and not as hex. Here is what I am sending:
body=%7b%22EmailAddress%22%3a%223%40blah.com%22%2c%22Name%22%3a%22bobby%22%2c%22CustomFields%22%3a%5b%7b%22Key%22%3a%22Country%22%2c%22Value%22%3a%22canada%22%7d%2c%7b%22Key%22%3a%22City%22%2c%22Value%22%3a%22vancouver%22%7d%5d%2c%22Resubscribe%22%3atrue%7d
Here is what I want to send:
{
"EmailAddress": "[email protected]",
"Name": "bobby",
"CustomFields" : [
{
"Key":"Country",
"Value":"canada"
},
{
"Key":"City",
"Value":"vancouver"
}
],
"Resubscribe": true
}
How can I pack this data so it is not going out as a string?
Upvotes: 2
Views: 1247
Reputation: 55012
Instead of:
request.set_form_data(:body => data)
Try it like this:
request.body = data
net/http should not be uri-encoding the post body, if you see that happening then maybe something else along the way is doing it or maybe you're just mistaken.
Upvotes: 2