Ruby使用标题机械化post

我有js页面,通过XMLHttpRequest发布数据和服务器端脚本检查此标头,如何发送此标头?

agent = WWW::Mechanize.new { |a| a.user_agent_alias = 'Mac Safari' a.log = Logger.new('./site.log') } agent.post('http://site.com/board.php', { 'act' => '_get_page', "gid" => 1, 'order' => 0, 'page' => 2 } ) do |page| p page end 

我发现这篇文章有网络搜索(两个月后,我知道),只是想分享另一个解决方案。

您可以使用预连接挂钩添加自定义标头而无需猴子修补Mechanize:

  agent = WWW::Mechanize.new agent.pre_connect_hooks << lambda { |p| p[:request]['X-Requested-With'] = 'XMLHttpRequest' } 

 ajax_headers = { 'X-Requested-With' => 'XMLHttpRequest', 'Content-Type' => 'application/json; charset=utf-8', 'Accept' => 'application/json, text/javascript, */*'} params = {'emailAddress' => 'me@my.com'}.to_json response = agent.post( 'http://example.com/login', params, ajax_headers) 

上面的代码适用于我(Mechanize 1.0)作为一种让服务器认为请求是通过AJAX发布的方式,但正如其他答案所述,它取决于服务器正在寻找的内容,它对于不同的框架/ js库会有所不同连击。

最好的办法是使用Firefox HTTPLiveHeaders插件或HTTPScoop ,查看浏览器发送的请求标头,然后尝试复制它。

看起来像早期版本的Mechanize,lambda有一个参数,但现在它有两个:

 agent = Mechanize.new do |agent| agent.pre_connect_hooks << lambda do |agent, request| request["Accept-Language"] = "ru" end end 

看一下文档 。

您需要使用Monkey-patch或从WWW::Mechanize派生自己的类来覆盖post方法,以便将自定义标头传递给私有方法post_form

例如,

 class WWW::Mechanize def post(url, query= {}, headers = {}) node = {} # Create a fake form class << node def search(*args); []; end end node['method'] = 'POST' node['enctype'] = 'application/x-www-form-urlencoded' form = Form.new(node) query.each { |k,v| if v.is_a?(IO) form.enctype = 'multipart/form-data' ul = Form::FileUpload.new(k.to_s,::File.basename(v.path)) ul.file_data = v.read form.file_uploads << ul else form.fields << Form::Field.new(k.to_s,v) end } post_form(url, form, headers) end end agent = WWW::Mechanize.new agent.post(URL,POSTDATA,{'custom-header' => 'custom'}) do |page| p page end