0

How can I call some webservices in rails 3 using POST params to an external URL? I usually use something like this to post from the command line

curl -X POST -u "v10REVkw:XuCqIhyCw" \
-H "Content-Type: application/json" \
--data '{"apids": ["c80-d363237c-e513b"], "android": {"alert": "Android  Test!"}}' \
https://url/to/push
ed1t
  • 8,719
  • 17
  • 67
  • 110

4 Answers4

2

I think I would use Rest client. Here is an example straight from their docs:

RestClient.post "http://example.com/resource", { 'x' => 1 }.to_json, :content_type => :json, :accept => :json
mikewilliamson
  • 24,303
  • 17
  • 59
  • 90
  • how do you pass username to it? – ed1t Apr 25 '11 at 01:16
  • If you are doing http basic auth you should be able to just slap it in the url: https://username:password@somesite.com. Github is helpfully making my fake link into a real one but you get the idea. – mikewilliamson Apr 25 '11 at 03:00
  • Additionally check out this other question: http://stackoverflow.com/questions/3692574/basic-auth-with-rest-client – mikewilliamson Apr 25 '11 at 03:16
0

Here is a detailled way to achieve what you expect extracted from one of my gems.

Just adapt and trigger with remote.

def remote
  begin
    Net::HTTP.get_response((uri)).body
  rescue 
    #what you want here
  end
end

def gateway
  'http://api.opencalais.com/enlighten/rest/'
end

def uri
  URI.parse(gateway + '?' + URI.escape(post_params.collect{ |k, v| "#{k}=#{v}" }.join('&')))
end

def post_params
  {
    'licenseID' => @api_key,
    'content'   => @context
  }
end

EDIT:

Be sure you have this included:

require 'uri'
require 'net/http'
require 'open-uri'

EDIT2:

If you're interacting with RESTful webservice, consider using ActiveResource

apneadiving
  • 114,565
  • 26
  • 219
  • 213
0

You can use ActiveResource, it is part of Rails package.

retro
  • 3,765
  • 2
  • 20
  • 37
0

Interesting enough that no-one hasn't so far suggested HTTParty, which is imho one of the simplest HTTP libs out there :)

http://httparty.rubyforge.org/

Tanel Suurhans
  • 1,632
  • 12
  • 11