什么是Ruby相当于这个curl请求?

时间:2014-01-14 10:35:11

标签: ruby curl faraday

我想要发布到api。这个文档中的示例适用于curl:

curl -k -w %{http_code} -H "Content-Type:text/plain" -u user:pass --data-binary @filename https://server/url/here

这是我用法拉第试过的:

require 'rubygems'
require 'faraday'
require 'pp'

conn = Faraday.new(:url => 'https://server/url/here' , :ssl => {:verify => false} ) do |faraday|
   faraday.response :logger
   faraday.basic_auth('user', 'pass')
   faraday.adapter  Faraday.default_adapter
 end

data = File.read('teste.txt')

res=conn.post '/' , data
pp res

它发布了,我收到了200个代码,但出了点问题。响应是服务器的登录页面。

curl -u是否等同于基本身份验证?

2 个答案:

答案 0 :(得分:3)

看起来正确,唯一的区别可能是标题中的内容类型,这应该有效:

require 'rubygems'
require 'faraday'
require 'pp'

conn = Faraday.new(:url => 'https://server/url/here' , :ssl => {:verify => false} ) do |faraday|
   faraday.response :logger
   faraday.basic_auth('user', 'pass')
   faraday.adapter  Faraday.default_adapter
 end

data = File.read('teste.txt')

res = conn.post do |req|
  req.headers['Content-Type'] = 'text/plain'
  req.body = data
end

pp res

答案 1 :(得分:0)

我知道你的问题涉及法拉第宝石,但这里我是如何使用'rest-client'宝石做的,也许这可以帮助:

response = RestClient.post "https://user:pass@server/url/here", data,
                           :content_type => 'text/plain'