Curl on Ruby on Rails
Asked Answered
T

3

18

how to use curl on ruby on rails? Like this one

curl -d 'params1[name]=name&params2[email]' 'http://mydomain.com/file.json'
Tatyanatau answered 4/4, 2013 at 6:53 Comment(5)
do u have a special requirment to use cUrl, coz I think you could use ruby HTTP post methodEllenaellender
#3811150Preciousprecipice
check this #11269724Ellenaellender
you should use Net::HTTP.Beacham
@Beacham Can you give me some example?Tatyanatau
T
37

Just in case you don't know, it requires 'net/http'

require 'net/http'

uri = URI.parse("http://example.org")

# Shortcut
#response = Net::HTTP.post_form(uri, {"user[name]" => "testusername", "user[email]" => "[email protected]"})

# Full control
http = Net::HTTP.new(uri.host, uri.port)

request = Net::HTTP::Post.new(uri.request_uri)
request.set_form_data({"user[name]" => "testusername", "user[email]" => "[email protected]"})

response = http.request(request)
render :json => response.body

Hope it'll helps others.. :)

Tatyanatau answered 5/4, 2013 at 5:44 Comment(0)
G
10

Here is a curl to ruby's net/http converter: https://jhawthorn.github.io/curl-to-ruby/

For instance, a curl -v www.google.com command is equivalent in Ruby to:

require 'net/http'
require 'uri'

uri = URI.parse("http://www.google.com")
response = Net::HTTP.get_response(uri)

# response.code
# response.body
Getaway answered 26/7, 2017 at 21:48 Comment(0)
H
0

The most basic example of what you are trying to do is to execute this with backticks like this

`curl -d 'params1[name]=name&params2[email]' 'http://mydomain.com/file.json'`

However this returns a string, which you would have to parse if you wanted to know anything about the reply from the server.

Depending on your situation I would recommend using Faraday. https://github.com/lostisland/faraday

The examples on the site are straight forward. Install the gem, require it, and do something like this:

conn = Faraday.new(:url => 'http://mydomain.com') do |faraday|
  faraday.request  :url_encoded             # form-encode POST params
  faraday.response :logger                  # log requests to STDOUT
  faraday.adapter  Faraday.default_adapter  # make requests with Net::HTTP
end

conn.post '/file.json', { :params1 => {:name => 'name'}, :params2 => {:email => nil} }

The post body will automatically be turned into a url encoded form string. But you can just post a string as well.

conn.post '/file.json', 'params1[name]=name&params2[email]'
Hydrogen answered 4/4, 2013 at 7:17 Comment(4)
uninitialized constant TestController::Faraday I's successfully install the gem.. what is the problem?Tatyanatau
Did you add the Gem to the Gemfile? and then run bundle install, usually those kidns of constant errors means it hasn't been loaded.Hydrogen
Yes I'm through with that.Tatyanatau
Could you post a pastie (pastie.org) of where you are putting the Faraday code?Hydrogen

© 2022 - 2024 — McMap. All rights reserved.