2011-04-24 24 views
0

如何使用POST參數在外部URL中調用rails 3中的某些webservices?我通常使用類似這樣的命令行POST在rails 3中

curl -X POST -u "v10REVkw:XuCqIhyCw" \ 
-H "Content-Type: application/json" \ 
--data '{"apids": ["c80-d363237c-e513b"], "android": {"alert": "Android Test!"}}' \ 
https://url/to/push 

回答

2

我認爲我會用Rest client。這裏是直接從他們的文檔的例子:

RestClient.post "http://example.com/resource", { 'x' => 1 }.to_json, :content_type => :json, :accept => :json 
+0

這是一個很好的資源,感謝分享:) +1;) – apneadiving 2011-04-24 15:51:34

+0

你如何傳遞用戶名? – ed1t 2011-04-25 01:16:04

+0

如果您正在進行http basic auth,您應該可以在url:https:// username:[email protected]上使用它。 Github正在幫助我的假鏈接變成真正的鏈接,但你明白了。 – mikewilliamson 2011-04-25 03:00:12

0

張貼這裏是一個的相關詳細的方式來實現你期望從我的寶石之一提取。

只適應並觸發remote

def remote 
    begin 
    Net::HTTP.get_response((uri)).body 
    rescue 
    #what you want here 
    end 
end 

def gateway 
    'http://api.opencalais.com/enlighten/rest/' 
end 

def uri 
    URI.parse(gateway + '?' + URI.escape(post_params.collect{ |k, v| "#{k}=#{v}" }.join('&'))) 
end 

def post_params 
    { 
    'licenseID' => @api_key, 
    'content' => @context 
    } 
end 

編輯:

要確保你有這包括:

require 'uri' 
require 'net/http' 
require 'open-uri' 

EDIT2:

如果你使用RESTful Web服務交互,可以考慮使用的ActiveResource

+0

的感謝!我只有一個問題,我如何在-u選項中傳遞? – ed1t 2011-04-24 15:51:24

+0

如果你想auth,更改網關如下:'http:// login:pass @ www.example.com/todo.cgi' – apneadiving 2011-04-24 15:55:43

+0

doc here:http://ruby-doc.org/stdlib/libdoc/net /http/rdoc/classes/Net/HTTP.html – apneadiving 2011-04-24 15:56:13