我是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的了解并不足以解决它。
答案 0 :(得分:3)
require 'net/http'
require 'net/https'
https = Net::HTTP.new('go.urbanairship.com', 443)
https.use_ssl = true
path = '/api/push'
答案 1 :(得分: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!')