Pass GET parameters with Ruby Curb

I am trying to use Curb (curb.rubyforge.org) to call a RESTful API that needs the parameters provided in the get request.

I want to get a url like http://foo.com/bar.xml?bla=blablabla . I would 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 do this is to manually include ?bla=blablabla in the URL and execute the encoding itself. Of course, there is the right way to do this, but I cannot figure it out by reading the documentation.

+4
source share
4 answers

If you don't mind using ActiveSupport '~> 3.0', there is a simple workaround - to_query , which converts the hash into a query string, ready for use in a 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 } 
+3
source

To pass parameters with a ruby ​​border, you can use

 Curl::postalize(params) 

These functions actually return to URI.encode_www_form (params) in the curb gem implementation. https://github.com/taf2/curb/blob/f89bb4baca3fb3482dfc26bde8f0ade9f1a4b2c2/lib/curl.rb

An example of using this function will be

 curl = Curl::Easy.new curl.url = "#{base_url}?#{Curl::postalize(params)}" curl.perform 

To access the curl return line you can use.

 data = curl.body_str 

The second alternative would be

 curl = Curl::Easy.new curl.url = Curl::urlalize(base_url, params) curl.perform data = curl.body_str 

Note that Curl :: urlalize may be a bit erroneous, see this pull for postalize, which fixed this flaw, but urlalize still uses the old implementation.

+7
source

How to just pass URI escape'd url for execution method (http_get)?

See http://www.ruby-doc.org/stdlib-1.9.3/libdoc/uri/rdoc/URI/Escape.html

 Curl::Easy.perform(URI.escape("http://foo.com/bar.xml?bla=blablabla").to_s) {|curl| curl.set_some_headers_if_necessary } 
+1
source

Have you considered another stone? rest-client works quite well and allows you to:

 RestClient.get 'http://example.com/resource', {:params => {:id => 50, 'foo' => 'bar'}} 

(I understand what you asked about Curb. I have no experience with Curb, sorry, the rest-client was pretty reliable every time I used it).

+1
source

Source: https://habr.com/ru/post/1380468/


All Articles