12
A
回答
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>
相關問題
- 1. 紅寶石HTTP POST參數
- 2. 紅寶石參數
- 3. 如何獲得紅寶石2.0模塊#prepend在紅寶石1.8?
- 4. 紅寶石ajax請求與參數
- 5. 紅寶石:參數與變量
- 6. 產卵與紅寶石參數
- 7. 獲取參數裏面的紅寶石
- 8. 與紅寶石
- 9. 與紅寶石
- 10. 與紅寶石
- 11. 與紅寶石
- 12. 與紅寶石
- 13. 紅寶石方法參數
- 14. 紅寶石參數錯誤
- 15. 紅寶石:在塊參數
- 16. 紅寶石 - 方法參數
- 17. 紅寶石instance_exec /帶參數
- 18. 「_」紅寶石的參數塊
- 19. 提取紅寶石參數
- 20. 得到紅寶石
- 21. 紅寶石參考
- 22. 紅寶石 - 問題與HTTP郵政
- 23. 可選參數/參數在紅寶石
- 24. 紅寶石`each_with_object`與指數
- 25. 紅寶石網/ http難點
- 26. 紅寶石HTTP請求
- 27. 紅寶石:HTTP PUT方法
- 28. HTTP請求紅寶石
- 29. 使用網:: HTTP紅寶石
- 30. REST與紅寶石?
你可以發佈你已經有的東西嗎? –
你想用這個請求做什麼?你想得到迴應嗎? –
你看過'net/http'文件嗎?如果是,那還不清楚? –