Net::HTTP.post_form

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 🙂