19

Somehow HTTParty returns 401 where CURL works fine. Not sure how to pass token in headers.

Working (200):

curl http://localhost:3020/api/products -H 'Authorization: Token token="111"'

Not working (401):

HTTParty.get('http://localhost:3020/api/products', headers: {"Authorization: Token token" => '111'})

I have tried with just "Authorization" => '111'and "token" => '111' but same result.

olimart
  • 1,529
  • 3
  • 17
  • 32

2 Answers2

39

Managed to get it working as follows.

HTTParty.get("http://localhost:3020/api/products", headers: {"Authorization" => "Token token=\"111\""})
mohamed-ibrahim
  • 10,837
  • 4
  • 39
  • 51
olimart
  • 1,529
  • 3
  • 17
  • 32
6

This also works if you want to set headers of the class dynamically, this example is for obtaining the Authorization token for Dun and Bradstreet

require 'httparty'

require 'certified'

class DnbAuth


  include HTTParty

  debug_output $stdout

  base_uri "https://maxcvservices.dnb.com/rest/Authentication"


  def initialize(ct,u,p)

    self.class.headers 'Content-type' =>  "#{ct}"

    self.class.headers 'x-dnb-user' => "#{u}"

    self.class.headers 'x-dnb-pwd'=> "#{p}"

  end


  def token()


    response = self.class.post("/")



  end





end


ct = 'text/xml'
u = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
p = 'xxxxxx'

xx = DnbAuth.new(ct,u,p)

puts xx.token.message
Conor
  • 494
  • 6
  • 15
  • 1
    You can also define headers in the same way as base_uri rather than doing it in the initialize method. Obviously provided it doesn't depend on any of the variables passed into the initialize method. For example you can use it to set an Authorization header for an API. – craig1410 Sep 09 '16 at 14:27