如何用Faraday正确设置含哈希与数组的X-Fantasy-Filter请求头?
解决Faraday中设置X-Fantasy-Filter请求头的问题
你的核心问题是直接将Ruby哈希赋值给请求头,而ESPN API要求X-Fantasy-Filter的值必须是紧凑的JSON字符串,Faraday不会自动将哈希序列化为JSON,直接传哈希会导致头信息格式错误,API无法解析。
修正后的代码
require 'json' url = "https://lm-api-reads.fantasy.espn.com/apis/v3/games/flb/seasons/2024/segments/0/leagues/xyz?&view=mScoreboard&view=mScoreboard&matchupPeriodId=2" begin response = Faraday.get(url) do |req| cookie_hash = {"swid" => "{xyx}", "espn_s2" => "xyz"} # 构造过滤条件哈希,转为紧凑JSON字符串 filter = {"schedule":{"filterMatchupPeriodIds":{"value":[2]}}} req.headers['X-Fantasy-Filter'] = filter.to_json.gsub(/\s+/, '') req.headers['Cookie'] = cookie_hash.map { |k, v| "#{k}=#{v}" }.join('; ') end rescue Exception => e puts "Failed: #{e}" end
关键要点
- JSON序列化:必须通过
Hash#to_json将Ruby哈希转为JSON字符串,不能直接赋值哈希对象。 - 紧凑格式要求:ESPN的API对
X-Fantasy-Filter的格式要求严格,需要去掉JSON中的所有空白字符(空格、换行等),避免解析失败。 - 异常处理修正:原代码将
rescue放在Faraday的block内部会导致语法错误,需将整个请求逻辑包裹在begin-rescue块中。
调试建议
可以在请求发送前打印请求头内容,确认格式是否正确:
puts req.headers['X-Fantasy-Filter'] # 正确输出应该是:{"schedule":{"filterMatchupPeriodIds":{"value":[2]}}}
内容的提问来源于stack exchange,提问作者user3007294
相关产品推荐
相关产品推荐

