如何在Ruby中编写带自定义头的POST请求?
Ruby HTTP客户端选择(适配带Basic Token的POST请求)
你需要发送携带静态Basic Token及自定义请求头的POST请求,以下是几个适合替换代码中client的Ruby HTTP客户端方案,附带具体实现:
需求参数回顾
- 认证头:
Authorization: Basic <insert token here> - API版本头:
X-Experience-API-Version: 1.0.3 - 客户端站点头:
X-Client-Site: <Provided by client>(假设对应client_site的头字段,可根据实际调整) - 请求体:JSON格式数据
1. Faraday(推荐,灵活易扩展)
Faraday是Ruby生态中广泛使用的HTTP客户端,支持中间件扩展,适配多种场景。
实现步骤
首先安装依赖:
gem install faraday
编写请求代码:
require 'faraday' require 'json' # 初始化客户端,配置基础URL和默认请求头 client = Faraday.new(url: "https://client-url") do |conn| conn.headers['Authorization'] = "Basic <insert token here>" conn.headers['X-Experience-API-Version'] = "1.0.3" conn.headers['X-Client-Site'] = "<Provided by client>" conn.adapter Faraday.default_adapter # 使用默认HTTP适配器 end # 发送POST请求 data = { /* 填充你的请求数据 */ } response = client.post("/xAPI/statements") do |req| req.headers['Content-Type'] = 'application/json' req.body = data.to_json end # 处理响应 puts response.status puts response.body
2. HTTParty(简洁直观)
HTTParty以简洁的语法著称,适合快速实现HTTP请求功能,无需复杂配置。
实现步骤
安装依赖:
gem install httparty
方式1:直接调用
require 'httparty' require 'json' data = { /* 填充你的请求数据 */ } response = HTTParty.post("https://client-url/xAPI/statements", headers: { 'Authorization' => "Basic <insert token here>", 'X-Experience-API-Version' => "1.0.3", 'X-Client-Site' => "<Provided by client>", 'Content-Type' => 'application/json' }, body: data.to_json ) puts response.code puts response.body
方式2:封装为客户端类(贴近你给出的client.post写法)
require 'httparty' require 'json' class XAPIClient include HTTParty base_uri "https://client-url" # 配置默认请求头 headers( 'Authorization' => "Basic <insert token here>", 'X-Experience-API-Version' => "1.0.3", 'X-Client-Site' => "<Provided by client>" ) end # 使用客户端发送请求 data = { /* 填充你的请求数据 */ } response = XAPIClient.post("/xAPI/statements", body: data.to_json, headers: { 'Content-Type' => 'application/json' })
3. Net::HTTP(原生库,无依赖)
如果不想引入第三方gem,可以使用Ruby自带的Net::HTTP库,无需额外安装。
require 'net/http' require 'json' uri = URI("https://client-url/xAPI/statements") http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true # HTTPS必须开启 request = Net::HTTP::Post.new(uri) request['Authorization'] = "Basic <insert token here>" request['X-Experience-API-Version'] = "1.0.3" request['X-Client-Site'] = "<Provided by client>" request['Content-Type'] = 'application/json' request.body = data.to_json response = http.request(request) puts response.code puts response.body
选择建议
- 若需要灵活扩展(如添加日志、重试中间件),优先选Faraday
- 若追求极简语法、快速实现,选HTTParty
- 若禁止引入第三方依赖,用Net::HTTP
内容的提问来源于stack exchange,提问作者Mag
相关产品推荐
相关产品推荐

