如何在Ruby中为Net::Http::Post请求添加头文件?

nwlls2ji  于 2023-08-04  发布在  Ruby
关注(0)|答案(2)|浏览(137)

我使用Rails 4.2.7。如何向Net::HTTP::Post请求添加头?我试过了

params = {"SubmitButton" => "View"}
    …
      headers = {"Referer" => url}
      req = Net::HTTP::Post.new(uri, params.to_query, headers)

字符串
但是当我运行这段代码时,我得到了错误

Error during processing: wrong number of arguments (given 3, expected 1..2)
/Users/davea/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/net/http/request.rb:14:in `initialize'
/Users/davea/Documents/workspace/myproject/app/services/marathon_guide_race_finder_service.rb:97:in `new'
/Users/davea/Documents/workspace/myproject/app/services/marathon_guide_race_finder_service.rb:97:in `block in process_race_link'
/Users/davea/.rvm/gems/ruby-2.3.0/gems/nokogiri-1.6.8/lib/nokogiri/xml/node_set.rb:187:in `block in each'
/Users/davea/.rvm/gems/ruby-2.3.0/gems/nokogiri-1.6.8/lib/nokogiri/xml/node_set.rb:186:in `upto'
/Users/davea/.rvm/gems/ruby-2.3.0/gems/nokogiri-1.6.8/lib/nokogiri/xml/node_set.rb:186:in `each'


注意我想在对象被发送之前将头添加到对象中。

nsc4cvqm

nsc4cvqm1#

您可以使用示例来创建带有标题的帖子

headers  = {"Referer" => url}
http     = Net::HTTP.new(uri.host)
response = http.post(uri.path, params.to_query, headers)

字符串

vxbzzdmp

vxbzzdmp2#

除了T J的方法(将头作为参数提供给post()调用)之外,您还可以使用:[]HTTPRequest对象本身上设置头:

uri = URI('http://example.com/cached_response')
req = Net::HTTP::Get.new(uri)
req['If-Modified-Since'] = file.mtime.rfc2822

字符串
来源:https://ruby-doc.org/stdlib-2.3.8/libdoc/net/http/rdoc/Net/HTTP.html#class-Net::HTTP-label-Setting+Headers
这允许您在执行请求之外设置标头。
同样的方法也适用于Net::HTTP::Post对象:

params = {"SubmitButton" => "View"}
req = Net::HTTP::Post.new(uri, params)
req['Referer'] = url

相关问题