2014-10-10 97 views
2

我想第一次學習Ruby。我有PHP和PHP的一些經驗,我做喜歡用於GET,POST,PUT,DELETE的Net :: HTTP的Ruby示例

function call_api(endpoint,method,arr_parameters='') 
{ 
// do a CURL call 
} 

一個功能,我會用像

call_api('https://api.com/user','get','param=1&param=2'); 
call_api('https://api.com/user/1','get'); 
call_api('https://api.com/user/1','post','param=1&param=2'); 
call_api('https://api.com/user/1','put','param=1&param=2'); 
call_api('https://api.com/user/1','delete'); 

到目前爲止,我只學會了如何做一個GET和POST調用與Ruby像這樣:

conn = Net::HTTP.new(API_URL, API_PORT) 
    resppost = conn.post("/user", 'param=1', {}) 
    respget = conn.get("/user?param=1",{}) 

但我不知道如何做刪除和放。有人可以顯示刪除的示例代碼並將調用與Net :: HTTP對象?

+1

有許多非常Ruby的良好HTTP gems,特別是Curb,它是libCurl的一個經過良好測試的包裝器。 https://www.ruby-toolbox.com/categories/http_clients有一個很好的列表,而不是試圖推出自己的,最好是利用其他人完成的工作。 – 2014-10-10 21:39:44

+1

Net :: HTTP設計相當糟糕,在我看來打破了很多Ruby約定。我第二@TheTinMan,並建議使用不同的http客戶端庫,如果你可以 – JKillian 2014-10-10 21:54:59

+0

嘿約翰做我的答案幫助? – Anthony 2014-10-13 17:25:37

回答

1

你只的命名空間:

Net::HTTP::Put.new(uri) 

同樣的,刪除:

Net::HTTP::Delete.new(uri) 

你甚至可以做到這一點與現有的電話:

conn = Net::HTTP.new(uri) 
con.get(path) 

,等效於:

Net::HTTP::Get.new(uri) 
1

對於刪除您可以使用conn.delete("/user/1", {})

request = Net::HTTP::Delete.new("/user/1") 
response = conn.request(request) 

對於PUT,

response = http.set_request('PUT', "/user/1", "param=1") 

Net::HTTP::Put.new(path)

1

我可以建議看看httparty?他們在頁面上提供了一些非常棒的例子,以完成你想要做的事情。

response = HTTParty.get('https://api.stackexchange.com/2.2/questions?site=stackoverflow') 

puts response.body, response.code, response.message, response.headers.inspect 

還有更多調用不同端點的例子。

3

我喜歡法拉第寶石。我發現它的設計最簡單。

一旦你gem install faraday可以require 'faraday'做:

result = Faraday.get('http://google.es') 

您還可以POST,PUT,DELETE等

Faraday.delete('http://google.es') 
Faraday.post('http://google.es', {some_parameter: 'hello'}) 

項目:https://github.com/lostisland/faraday

相關問題