0

I'm pretty new in Ruby and Rails.

I want to send a HTTP POST request in my rails application, the request can be invoked by command line like:

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

The ruby code I wrote (actually it's glue code) is:

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

However, running the ruby code in Rails Console didn't give me expected result (the command line does). Can someone give me a hand? I've tried searching relevant posts and Ruby docs, however my knowledge in Ruby is not good enough to solve it.

Arup Rakshit
  • 116,827
  • 30
  • 260
  • 317
Chris Chen
  • 5,307
  • 4
  • 45
  • 49

2 Answers2

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

https = Net::HTTP.new('go.urbanairship.com', 443)
https.use_ssl = true
path = '/api/push'
Andrew Cazares
  • 106
  • 1
  • 2
1

It's often tidier to create a little client class. I like HTTParty for that:

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

Then you use it like so:

UAS.alert('Hello!')
Mark Thomas
  • 37,131
  • 11
  • 74
  • 101