[英]HttParty: set default header for all requests
In some HTTP Clients theres one way to do something like:在某些 HTTP 客户端中,有一种方法可以执行以下操作:
HttpClient.default_headers = { "my-header": "a-value" }
And then every request done with that client will include those headers.然后该客户端完成的每个请求都将包含这些标头。
Is there any way to do this with jnunemaker/httparty ?有没有办法用jnunemaker/httparty做到这一点?
There is!有!
class MyIntegrationClass
include HTTParty
base_uri 'https://somedomain.com/api'
headers 'my-header' => 'a-value'
def some_method
response = get('/endpoint')
JSON.parse(response.to_s, symbolize_names: true)
end
end
The get request will have the my-header
header set.获取请求将设置my-header
标头。
I found one way to make this work running without having to use class methods:我找到了一种无需使用 class 方法即可使这项工作运行的方法:
HTTParty::Basement.headers 'my-header' => 'a value'
You could use it with hooks like this:您可以将它与这样的钩子一起使用:
require "httparty"
module DefaultHeadersForHttparty
extend ActiveSupport::Concern
included do
before_action :apply_http_party_headers
private
def apply_http_party_headers
HTTParty::Basement.headers 'my-header' => 'a value'
end
end
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.