如何在Ruby中使用Mechanize或Faraday发送JSON表单数据

时间:2014-02-27 09:02:06

标签: ruby-on-rails ruby json mechanize faraday

我想从使用JSON数据的网站检索数据,以设置似乎是通过AJAX请求的自定义搜索参数。传输的数据显示在XHR-> Firebug中的请求有效负载:

{"filters": [{"action": "post", "filterName": "Hersteller", "ids": [269], 
"settingName": "Hersteller", "settingValue": "ValueA"}, 
{"action": "delete", "filterName": "Modelle", 
"settingName": "Modelle", "settingValue": ""}]}

该站点不传输任何POST参数,只传输此JSON编码数据以应用搜索条件。使用Mechanize将此数据作为post参数传递不起作用。

如何在Ruby on Rails中使用Mechanize或Faraday传输这些数据?

2 个答案:

答案 0 :(得分:11)

使用Mechanize,您可以:

agent.post url, data.to_json, {'Content-Type' => 'application/json'}

答案 1 :(得分:0)

我找到了一种方法:

connection = Faraday.new

fetched_page = connection.post do |request|
  request.url 'http://www.site.com'
  request.headers['Content-Type'] = 'application/json'
  request.body = '{"filters": [{"action": "post", "filterName": "Hersteller", "ids": [269], 
"settingName": "Hersteller", "settingValue": "ValueA"}, {"action": "delete", "filterName": "Modelle", "settingName": "Modelle", "settingValue": ""}]}'
end