2011-07-27 53 views
12

我怎样才能发送HTTP GET请求通过参数通过红宝石?红宝石HTTP获得与参数

我试了很多例子,但都失败了。

+2

你可以发布你已经有的东西吗? –

+0

你想用这个请求做什么?你想得到回应吗? –

+3

你看过'net/http'文件吗?如果是,那还不清楚? –

回答

6

我假定您了解Net::HTTP documentation page上的示例,但是您不知道如何将参数传递给GET请求。

你刚才的参数追加到请求的地址,在完全相同的方式,你在浏览器中输入该地址:

require 'net/http' 

res = Net::HTTP.start('localhost', 3000) do |http| 
    http.get('/users?id=1') 
end 
puts res.body 

如果你需要从一个哈希构建参数字符串一些通用的方法,你可以创建这样一个帮手:

require 'cgi' 

def path_with_params(page, params) 
    return page if params.empty? 
    page + "?" + params.map {|k,v| CGI.escape(k.to_s)+'='+CGI.escape(v.to_s) }.join("&") 
end 

path_with_params("/users", :id => 1, :name => "John&Sons") 
# => "/users?name=John%26Sons&id=1" 
14

我知道这个职位是旧的,但对于那些通过谷歌带到这里的缘故,有编码的URL安全的方式您的参数更简单的方法。我不确定为什么我没有在其他地方看到这个方法,因为这个方法在Net :: HTTP页面上有记录。我也看到了Arsen7所描述的方法也被认为是其他几个问题的答案。

Net::HTTP文件中所提及的URI.encode_www_form(params)

# Lets say we have a path and params that look like this: 
path = "/search" 
params = {q: => "answer"} 

# Example 1: Replacing the #path_with_params method from Arsen7 
def path_with_params(path, params) 
    encoded_params = URI.encode_www_form(params) 
    [path, encoded_params].join("?") 
end 

# Example 2: A shortcut for the entire example by Arsen7 
uri = URI.parse("http://localhost.com" + path) 
uri.query = URI.encode_www_form(params) 
response = Net::HTTP.get_response(uri) 

哪个例子你选择的是对你的使用情况非常依赖。在我目前的项目中,我使用的方法类似于Arsen7推荐的方法,以及更简单的#path_with_params方法,没有块格式。

# Simplified example implementation without response 
# decoding or error handling. 

require "net/http" 
require "uri" 

class Connection 
    VERB_MAP = { 
    :get => Net::HTTP::Get, 
    :post => Net::HTTP::Post, 
    :put => Net::HTTP::Put, 
    :delete => Net::HTTP::Delete 
    } 

    API_ENDPOINT = "http://dev.random.com" 

    attr_reader :http 

    def initialize(endpoint = API_ENDPOINT) 
    uri = URI.parse(endpoint) 
    @http = Net::HTTP.new(uri.host, uri.port) 
    end 

    def request(method, path, params) 
    case method 
    when :get 
     full_path = path_with_params(path, params) 
     request = VERB_MAP[method].new(full_path) 
    else 
     request = VERB_MAP[method].new(path) 
     request.set_form_data(params) 
    end 

    http.request(request) 
    end 

    private 

    def path_with_params(path, params) 
    encoded_params = URI.encode_www_form(params) 
    [path, encoded_params].join("?") 
    end 

end 

con = Connection.new 
con.request(:post, "/account", {:email => "[email protected]"}) 
=> #<Net::HTTPCreated 201 Created readbody=true>