Curl on Ruby on Rails

前端 未结 3 1056
无人及你
无人及你 2020-12-15 22:05

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

curl -d \'params1[name]=name¶ms2[email]\' \'http://mydomain.com/file.json\'
3条回答
  •  眼角桃花
    2020-12-15 22:52

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

    `curl -d 'params1[name]=name¶ms2[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¶ms2[email]'
    

提交回复
热议问题