2011-12-15 84 views
0

我很新的Ruby和Rails。如何在ruby中编写这个HTTPS POST请求?

我想向我的Rails应用程序HTTP POST请求,该请求可以通过命令行一样调用:

curl -X POST -u "username:password" \ 
    -H "Content-Type: application/json" \ 
    --data '{"device_tokens": ["0C676037F5FE3194F11709B"], "aps": {"alert": "Hello!"}}' \ 
    https://go.urbanairship.com/api/push/ 

我写的(实际上这是胶水代码)的Ruby代码是:

uri = URI('https://go.urbanairship.com/api/push') 
Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') do |http| 
    request = Net::HTTP::Post.new(uri.request_uri, initheader = {'Content-Type' =>'application/json'}) 
    request.basic_auth 'username', 'password' 
    request.body = ActiveSupport::JSON.encode({'device_tokens' => ["4872AAB82341AEE600C6E219AA93BB38B5144176037F2056D65FE3194F11709B"], "aps" => {"alert" => "Hello!"}}) 
    response = http.request request # Net::HTTPResponse object 
    puts response.body 
end 

但是,在Rails控制台中运行ruby代码并没有给我预期的结果(命令行)。有人能帮我一把吗?我试过搜索相关文章和Ruby文档,但是我在Ruby中的知识还不够好来解决它。

+1

也许这个问题就能帮助你http://stackoverflow.com/questions/1719809/ruby-on -rails-https-post-bad-request – kaissun 2011-12-15 13:32:15

回答

1

创建一个小客户端类通常更加整洁。我喜欢HTTParty为:

require 'httparty' 

class UAS 
    include HTTParty 

    base_uri "https://go.urbanairship.com" 
    basic_auth 'username', 'password' 
    default_params :output => 'json' 
    @token = "4872AAB82341AEE600C6E219AA93BB38B5144176037F2056D65FE3194F11709B" 

    def self.alert(message) 
    post('/api/push/', {'device_tokens' => @token, 'aps' => {"alert" => message}}) 
    end 
end 

然后你使用它像这样:

UAS.alert('Hello!') 
3
require 'net/http' 
require 'net/https' 

https = Net::HTTP.new('go.urbanairship.com', 443) 
https.use_ssl = true 
path = '/api/push'