如何使用适配器防止法拉第更改大写标题

问题描述 投票:0回答:1

我正在使用Faraday创建将与API交互的SDK,我需要发送两个标头API_SIGNATURE和API_REQUEST_TIME,所以这就是我创建的:

class APIClient
  def initialize(api_key)
    @api_key = api_key
  end

  def get_users
    request.post('/users')
  end

  private

  def request
    Faraday.new(@@BASE_API_URL, headers: headers)
  end

  def headers
    timestamp = Time.now.to_i.to_s
    return {
      'API_SIGNATURE': Digest::MD5.hexdigest(@api_key + timestamp),
      'API_REQUEST_TIME': timestamp
    }
  end
end

由于某种原因,法拉第将API_SIGNATURE更改为Api-Signature,将API_REQUEST_TIME更改为Api-Request-Time

我想防止这种情况的发生。建议有人使用赞助人:

  def request
    Faraday.new(@@BASE_API_URL, headers: headers) do |faraday|
      faraday.adapter :patron
    end
  end

但是那不起作用。引发以下错误:

/Users/me/.rvm/gems/ruby-2.4.9/gems/patron-0.13.3/lib/patron/session.rb:330:in `handle_request': Operation timed out after 1004 milliseconds with 0 out of 0 bytes received (Faraday::TimeoutError)
        from /Users/me/.rvm/gems/ruby-2.4.9/gems/patron-0.13.3/lib/patron/session.rb:330:in `request'
        from /Users/me/.rvm/gems/ruby-2.4.9/gems/faraday-0.17.0/lib/faraday/adapter/patron.rb:29:in `call'
        from /Users/me/.rvm/gems/ruby-2.4.9/gems/faraday-0.17.0/lib/faraday/rack_builder.rb:143:in `build_response'
        from /Users/me/.rvm/gems/ruby-2.4.9/gems/faraday-0.17.0/lib/faraday/connection.rb:387:in `run_request'
        from /Users/me/.rvm/gems/ruby-2.4.9/gems/faraday-0.17.0/lib/faraday/connection.rb:175:in `post'
        from api.rb:32:in `analyze_text'
        from api.rb:38:in `full_analysis'
        from api.rb:65:in `<main>'

谢谢。

=======更新==========

问题减少:

headers = { API_SIGNATURE: '', API_REQUEST_TIME: '' }

conn = Faraday.new('https://api.test.io', headers: headers) do |f|
  f.adapter :patron
end

puts conn.headers
ruby adapter faraday
1个回答
1
投票
发生此错误是因为Faraday默认使用Net :: HTTP和Net::HTTP changes the case of your header keys。您可以在this related question上阅读有关此问题的更多信息。
© www.soinside.com 2019 - 2024. All rights reserved.