Net::HTTP.post_form
Posted: January 18th, 2007 | Author: Joakim Andersson | Filed under: ruby | 4 Comments »Maybe I didn’t get how it works but I can’t get the Net::HTTP.post_form method in the ruby library to post to a URL like this, http://foo.bar/foo.php?q=search, i.e. a URL with GET query parameters.
The post_form method takes an URI instance (which you get with something like u = URI.parse(“http://foo.bar/foo.php?q=search”)) and then the code works like this:
def HTTP.post_form(url, params)
req = Post.new(url.path)
req.form_data = params
req.basic_auth url.user, url.password if url.user
new(url.host, url.port).start {|http|
http.request(req)
}
end
You see the use of url.path there then creating the Post object? That won’t include the ?q=search part of the url.
I’m not sure if this is the way it’s designed to work but I haven’t been able to figure out a way to mark any parameter I send in to the post_form method in params as a GET parameter. If that was possible this would work fine but for now I’ve settled on the below piece of code:
def my_post_form(url, params)
req = Net::HTTP::Post.new(url.request_uri)
req.form_data = params
req.basic_auth url.user, url.password if url.user
Net::HTTP::new(url.host, url.port).start {|http|
http.request(req)
}
end
which will do for me until you all tell me how stupid I am and give me a better solution :)
Hi
The post_form method posts data off to the URL. GET and POST requests are completely separate.
Eg you can post data off to a URL complete with a GET querystring. http://my-site.com?key=value that is a GET request, so the key/value pair are sent as part of the URL, whereas you could post that key/value pair and use the URL http://my-site.com and the values are submitted in the Headers to the server
Unfortunately it’s not that simple. Consider the following PHP script:
<?php echo “Get:\n”; var_dump($_GET); echo “Post:\n”; var_dump($_POST); ?>
It first prints the GET parameters received from the URL and then the POST parameters.
If we now run the following curl command:
$ curl -d foo=bar http://localhost/~joakim/echo.php
which simulates a POST request, we get the expected output:
Get: array(0) { } Post: array(1) { ["foo"]=> string(3) “bar” }
But if we do this, i.e. we POST to a URL with query parameters
$ curl -d foo=bar http://localhost/~joakim/echo.php?key=value
we get:
Get: array(1) { ["key"]=> string(5) “value” } Post: array(1) { ["foo"]=> string(3) “bar” }
That’s the problem for me, the place I try to post a form to with Net::HTTP.post_form is doing an explicit check for a GET parameter then handling the POST request, and with the current implementation of Net::HTTP.post_form is seems to be impossible to send both GET and POST parameters at the same time.
Nice job. To use url = URI.parse(‘http://l/schools/kendall?q=ruby‘) then my_post_form(url, {“r” => “m”})
Thank You,