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