2

我正在尝试编写一个简单的 http 帖子,它将一个 json 正文发送到一个 restful api。我正在使用以下代码:

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

我遇到的麻烦是正文以字符串而不是十六进制形式发送到服务器。这是我要发送的内容:

正文=%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%22重新订阅%22%3atrue%7d

这是我要发送的内容:

{
  "EmailAddress": "3@blah.com",
  "Name": "bobby",
  "CustomFields" : [
    {
      "Key":"Country",
      "Value":"canada"
    },
    {
      "Key":"City",
      "Value":"vancouver"
    }
  ],
  "Resubscribe": true
}

如何打包这些数据,使其不作为字符串输出?

4

1 回答 1

2

代替:

request.set_form_data(:body => data)

试试这样:

request.body = data

net/http 不应该对帖子正文进行 uri 编码,如果您看到这种情况发生,那么可能还有其他事情正在这样做,或者您可能只是弄错了。

于 2012-07-28T07:37:37.433 回答