在 Ruby on Rails 上卷曲

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15804425/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 21:44:56  来源:igfitidea点击:

Curl on Ruby on Rails

ruby-on-railsruby-on-rails-3curlruby-on-rails-3.1

提问by Lian

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

如何在轨道上的红宝石上使用卷曲?像这个

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

回答by Lian

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

以防万一你不知道,它需要'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.. :)

希望它会帮助别人.. :)

回答by Benjamin J. Benoudis

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

这是 ruby​​ 的 net/http 转换器的 curl:https: //jhawthorn.github.io/curl-to-ruby/

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

例如,一个curl -v www.google.com命令在 Ruby 中等效于:

require 'net/http'
require 'uri'

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

# response.code
# response.body

回答by stuartc

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

根据您的情况,我建议使用法拉第。https://github.com/lostisland/faraday

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

网站上的例子很简单。安装 gem,需要它,然后执行如下操作:

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.

帖子正文将自动转换为 url 编码的表单字符串。但是你也可以只发布一个字符串。

conn.post '/file.json', 'params1[name]=name&params2[email]'