Ruby mechanize post with header

前端 未结 4 462
梦如初夏
梦如初夏 2021-02-04 14:14

I have page with js that post data via XMLHttpRequest and server side script check for this header, how to send this header?

agent = WWW::Mechanize.new { |a|
  a         


        
4条回答
  •  生来不讨喜
    2021-02-04 14:23

    Take a look at the documentation.

    You need to either monkey-patch or derive your own class from WWW::Mechanize to override the post method so that custom headers are passed through to the private method post_form.

    For example,

    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
    

提交回复
热议问题