How to send JSON form data with Mechanize or Faraday in Ruby

拈花ヽ惹草 提交于 2019-12-06 07:04:51

问题


I want to retrieve data from a website that uses JSON data to set custom search parameters which seem to be requested via AJAX. The data transmitted shows up under XHR->Request Payload in Firebug:

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

The site doesn't transmit any POST parameters but only this JSON encoded data to apply search criteria. Passing this data as post parameters with Mechanize doesn't work.

How can this data be transmitted using Mechanize or Faraday in Ruby on Rails?


回答1:


With Mechanize you would do:

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



回答2:


I figured out a way to do this:

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


来源:https://stackoverflow.com/questions/22063646/how-to-send-json-form-data-with-mechanize-or-faraday-in-ruby

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!