2011-07-27 54 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>