Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTTP.post_form in Ruby with custom headers

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?

I use

resp, data = Net::HTTP.post_form(url, query)

How would I change this to throw custom headers in?

Edit my query is:

query = {'a'=>'b'}
like image 395
Tarang Avatar asked May 16 '26 05:05

Tarang


2 Answers

You can try this, for example:

http = Net::HTTP.new('domain.com', 80)
path = '/url'

data = 'form=data&more=values'
headers = {
  'Cookie' => cookie,
  'Content-Type' => 'application/x-www-form-urlencoded'
}

resp, data = http.post(path, data, headers)
like image 170
Sergio Tulentsev Avatar answered May 18 '26 20:05

Sergio Tulentsev


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)

like image 40
sarahhodne Avatar answered May 18 '26 18:05

sarahhodne