【问题标题】:How to write this HTTPS POST request in ruby?如何用 ruby​​ 编写这个 HTTPS POST 请求?
【发布时间】:2012-01-21 04:35:24
【问题描述】:

我是 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 知识不足以解决它。

【问题讨论】:

标签: ruby ruby-on-rails-3 net-http


【解决方案1】:
require 'net/http'
require 'net/https'

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

【讨论】:

    【解决方案2】:

    创建一个小的客户端类通常更整洁。我喜欢 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!')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-25
      • 1970-01-01
      • 1970-01-01
      • 2023-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多