问题描述
我想使用Curb(curb.rubyforge.org)来调用一个需要在get请求中提供参数的RESTful API。
I'm trying to use Curb (curb.rubyforge.org) to call a RESTful API that needs parameters supplied in a get request.
我想抓取像 http://foo.com/bar.xml?bla=blablabla
的网址。我想要能够做像
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
}
但到目前为止,看到这样做是通过手动包括?bla = blablabla
在URL和自己做编码。当然有一个正确的方法来做到这一点,但我不能弄清楚阅读文档。
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.
推荐答案
使用ActiveSupport'〜> 3.0',有一个简单的解决方法 - to_query
方法,将hash转换为可以在URL中使用的查询字符串。
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
}
这篇关于使用Ruby Curb传递GET参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!