2011-07-27 20 views
12

Parametrelerle HTTP GET isteğini ruby ​​ile nasıl gönderebilirim?Ruby HTTP params ile alın

Çok fazla örnek denedim ama hepsi başarısız oldu.

+2

Zaten sahip olduğunuz bir şeyi gönderebilir misiniz? –

+0

Bu istek ile ne yapmak istersiniz? cevabı almak ister misin? –

+3

'net/http' belgelerine baktınız mı? Eğer evet ise, hala ne belirsiz? –

cevap

6

Net::HTTP documentation page'daki örnekleri anladığınızı ama parametreleri GET isteğine nasıl ileteceğinizi bilmediğinizi varsayalım.

sadece tamamen aynı şekilde tarayıcıda böyle adresini yazın, istenen adrese parametreler ekleme:

require 'net/http' 

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

bir karma gelen parametreleri dize oluşturmak için bazı genel yolu gerekiyorsa, böyle bir yardımcı yaratabilir:

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

Bu yazı eski olduğunu biliyorum ama google tarafından buraya getirilen olanlar uğruna, bir URL güvenli bir şekilde parametrelerinizi kodlamak için daha kolay bir yolu yoktur. Yöntemin Net :: HTTP sayfasında belgelenmesi nedeniyle bunu neden başka bir yerde görmediğimi bilmiyorum. Arsen7 tarafından açıklanan diğer birçok soruya da kabul edilen cevap olarak gördüğüm yöntemi gördüm. Net::HTTP belgelerinde bahsetti

URI.encode_www_form(params) şudur: çok bağımlı kullanımı durumda olduğunu seçmek örnek

# 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) 

. Benim şu anki projemde, Arsen7 tarafından tavsiye edilene benzer bir yöntemle, daha basit #path_with_params yöntemiyle ve blok formatı olmadan kullanıyorum.

# 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>