What is the Ruby equivalent to this curl request?

元气小坏坏 提交于 2020-01-01 05:59:20

问题


I'm tring to post to an api. This example from the docs works in curl:

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

This is what I have tried with faraday:

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

It posts, I receive a 200 code but something goes wrong. The response is the server's login page.

Is curl -u equivalent to basic auth?


回答1:


That looks right, the only difference is possibly the content-type in the header, this should work:

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



回答2:


I know your question concerns the Faraday gem but here is how I would have done it using the 'rest-client' gem, maybe this can help:

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


来源:https://stackoverflow.com/questions/21111347/what-is-the-ruby-equivalent-to-this-curl-request

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!