带有自定义标题和正文的Ruby POST?

时间:2016-05-12 01:57:57

标签: ruby-on-rails ruby json http ssl

我正在尝试在Ruby中POST到Mailchimp,但是我无法获得任何具有自定义标题和正文的代码。这是我试图复制的请求:

curl --request GET \
--url 'https://<dc>.api.mailchimp.com/3.0/' \
--user 'anystring:<your_apikey>'

但我还必须添加一个JSON正文。

如果我运行此代码:

postData = Net::HTTP.post_form(URI.parse('https://xxx.api.mailchimp.com/3.0/lists/xxx/members/'), { ... }})
puts postData.body

我收到Mailchimp的回复,说明apikey丢失了。如何添加API密钥?

根据这些帖子: Ruby request to https - "in `read_nonblock': Connection reset by peer (Errno::ECONNRESET)"

Ruby send JSON request

我试过了:

uri = URI('https://xxx.api.mailchimp.com/3.0/lists/xxxx/members/')
req = Net::HTTP::Post.new(uri, initheader = {'Content-Type' =>'application/json'})
req.basic_auth 'anystring', 'xxxx'
req.body = URI.encode_www_form({ ... }})
response = Net::HTTP.new(uri.hostname, uri.port, :use_ssl => uri.scheme == 'https').start {|http| http.request(req) }
puts "Response #{response.code} #{response.message}:#{response.body}"

但我在TypeError (no implicit of Hash into String)行收到错误response = ...。引用的错误是什么以及如何解决?

更新:

使用start代替new

response = Net::HTTP.start(uri.hostname, uri.port, :use_ssl => uri.scheme == 'https') {|http| http.request(req) }

我能够发送请求,但是我收到了400响应:“我们遇到了一个未指定的JSON解析错误”

我对发布的答案得到了同样的答复。这是我的JSON:

{'email_address' => 'xxxx@gmail.com', 'status' => 'subscribed', 'merge_fields' => {'FNAME' => 'xxx', 'LNAME' => 'xxx' }

我也试过添加这样的数据:

req.set_form_data('email_address' => 'xxxx@gmail.com', 'status' => 'subscribed', 'merge_fields' => {'FNAME' => 'xxx', 'LNAME' => 'xxx' } )

但是我得到了相同的JSON解析错误

1 个答案:

答案 0 :(得分:2)

试试这个,如果它适合你

uri = URI('https://api.mailchimp.com/3.0/lists/xxxx/members/')

Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') do |http|
  req = Net::HTTP::Post.new(uri)
  req['Content-Type'] = 'application/json'
  req.basic_auth 'username', 'password'
  req.set_form_data('from' => '2005-01-01', 'to' => '2005-03-31')

  response = http.request req # Net::HTTPResponse object
end

您需要在post请求中设置表单数据,如

req.set_form_data('from' => '2005-01-01', 'to' => '2005-03-31')

<强>更新

尝试发布原始数据,例如

json_data = {'from' => '2005-01-01', 'to' => '2005-03-31'}.to_json
req.body = json_data