Curl on Ruby on Rails

17

如何在Ruby on Rails中使用curl?像这样

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

你是否有使用cUrl的特殊要求?因为我认为你可以使用Ruby的HTTP POST方法。 - sameera207
http://stackoverflow.com/questions/3810650/help-me-converting-this-curl-to-a-post-method-in-rails - Sachin R
1
请查看此链接:https://dev59.com/nGgu5IYBdhLWcg3wgnVh - sameera207
1
你应该使用 Net::HTTP - shweta
@shweta 你能给我一些例子吗? - Lian
3个回答

36

如果你不知道的话,需要引入 'net/http' 库

require 'net/http'

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

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

# 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]" => "testemail@yahoo.com"})

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

希望这会对其他人有所帮助.. :)


10
这里有一个将curl转换为Ruby的net/http的工具:https://jhawthorn.github.io/curl-to-ruby/ 例如,一个 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

0
您要尝试做的最基本的示例是像这样使用反引号执行它
`curl -d 'params1[name]=name&params2[email]' 'http://mydomain.com/file.json'`

然而,这会返回一个字符串,如果你想知道服务器的回复信息,你需要解析它。

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

网站上的示例很简单。安装 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} }

帖子正文将自动转换为URL编码的表单字符串。 但您也可以直接发布字符串。

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

未初始化常量TestController :: Faraday。我已成功安装宝石..问题出在哪里? - Lian
你是否将Gem添加到了Gemfile中?然后运行bundle install,通常这种持续出现的错误意味着它还没有被加载。 - stuartc
是的,我已经完成了。 - Lian
你能否在 Pastie(http://pastie.org/) 上分享一下你放置 Faraday 代码的位置? - stuartc

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接