Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: Can net/http make a GET and POST request simultaneously?

Tags:

uri

ruby

Is it possible to pass both the GET and POST parameters at the same time?

uri = URI.parse("http://www.example.com/post.php?a=1&b=2")

req = Net::HTTP::Post.new(uri.path, {
    'Referer' => "http://www.example.com/referer",
    'User-Agent'=> "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)",
    'Cookie' => $cookie
})

req.set_form_data({
    'foo' => 'bar',
    'bar' => 'foo'
})

http = Net::HTTP.new(uri.host, uri.port)
http.open_timeout = 40
http.read_timeout = 20

# Request page:
begin
    resp = http.request(req)
rescue Exception
    puts "Exception requesting the page; returning"
end

In the script above, only the POST parameters get sent and the GET query is ignored

like image 448
Marco Avatar asked Jun 06 '10 22:06

Marco


1 Answers

When creating the request you just need to make sure to keep the GET params in the path:

req = Net::HTTP::Post.new("#{uri.path}?#{uri.query}", {
    'Referer' => "http://www.example.com/referer",
    'User-Agent'=> "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)",
    'Cookie' => $cookie
})

Notice that instead of just uri.path, I append the ? and uri.query to it. This should pass the GET parameters as well as the POST ones.

like image 108
Mitchell Avatar answered Oct 13 '22 11:10

Mitchell