0

我是 Ruby 和 Rails 的新手。

我想在我的 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 方面的知识不足以解决它。

4

2 回答 2

3
require 'net/http'
require 'net/https'

https = Net::HTTP.new('go.urbanairship.com', 443)
https.use_ssl = true
path = '/api/push'
于 2011-12-15T14:30:39.653 回答
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!')
于 2011-12-15T14:56:03.197 回答