5

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?

Alex Takitani
  • 491
  • 5
  • 14
  • duplicated with this http://stackoverflow.com/questions/929652/equivalent-of-curl-for-ruby?rq=1 – Thomas Tran Jan 14 '14 at 10:48
  • I cant see where it is duplicated. – Alex Takitani Jan 14 '14 at 10:49
  • sorry, forget it. Could you provide the actual API URL? – Thomas Tran Jan 14 '14 at 11:17
  • According to the curl man page: "-u, --user Specify the user name and password to use for server authentication.", so it should be equivalent to HTTP Basic Auth. Note however, that the site's login page has nothing to do with HTTP Basic Auth, it is a separate layer of authentication. – Patrick Oscity Jan 14 '14 at 11:40

2 Answers2

5

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
Peter Souter
  • 5,110
  • 1
  • 33
  • 62
1

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'
Nanego
  • 1,890
  • 16
  • 30