HTTP.post_form in Ruby with custom headers

前端 未结 4 939
刺人心
刺人心 2021-01-14 20:07

Im trying to use Nets/HTTP to use POST and put in a custom user agent. I\'ve typically used open-uri but it cant do POST can it?

4条回答
  •  情话喂你
    2021-01-14 20:26

    You can't use post_form to do that, but you can do it like this:

    uri = URI(url)
    req = Net::HTTP::Post.new(uri.path)
    req.set_form_data(query)
    req['User-Agent'] = 'Some user agent'
    
    res = Net::HTTP.start(uri.hostname, uri.port) do |http|
      http.request(req)
    end
    
    case res
    when Net::HTTPSuccess, Net::HTTPRedirection
      # OK
    else
      res.value
    end
    

    (Read the net/http documentation for more info)

提交回复
热议问题