I'm trying to use Curb (curb.rubyforge.org) to call a RESTful API that needs parameters supplied in a get request.
I want to fetch a URL like http://foo.com/bar.xml?bla=blablabla
. I'd like to be able to do something like
Curl::Easy.perform("http://foo.com/bar.xml", :bla => 'blablabla') {|curl|
curl.set_some_headers_if_necessary
}
but so far, the only way I can see to do this is by manually including the ?bla=blablabla
in the URL and doing the encoding myself. Surely there is a right way to do this, but I can't figure it out reading the documentation.
To pass get parameters with the ruby curb gem you could use
Curl::postalize(params)
This functions actually falls back to URI.encode_www_form(params) in the curb gem implementation. https://github.com/taf2/curb/blob/f89bb4baca3fb3482dfc26bde8f0ade9f1a4b2c2/lib/curl.rb
An example on how to use this would be
curl = Curl::Easy.new
curl.url = "#{base_url}?#{Curl::postalize(params)}"
curl.perform
To access the curl return string you could use.
data = curl.body_str
The second alternatives would be
curl = Curl::Easy.new
curl.url = Curl::urlalize(base_url, params)
curl.perform
data = curl.body_str
Do note that Curl::urlalize might be slightly flawed see this pull for postalize that has fix this flaw but the urlalize still uses the old implementation.
If you don't mind using ActiveSupport '~> 3.0', there's an easy workaround - to_query
method, which converts hash to query string ready to be used in URL.
# active_support cherry-pick
require 'active_support/core_ext/object/to_query'
params = { :bla => 'blablabla' }
Curl::Easy.perform("http://foo.com/bar.xml?" + params.to_query) {|curl|
curl.set_some_headers_if_necessary
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With