使用Ruby调用Twitter API v2发推时触发OAuth请求报错
问题根因
运行抛出OAuth::RequestProxy::UnknownRequestType错误的直接原因是:你使用的oauth gem默认没有内置Typhoeus::Request类型的请求代理适配,直接将Typhoeus实例传入OAuth::Client::Helper时,签名模块无法解析请求结构,无法生成合法的OAuth授权头。
另外你的代码还有一处隐藏错误:发推请求的body格式不符合接口要求。你当前JSON.dump("Hello, world!")生成的是纯JSON字符串,而Twitter v2发推接口要求请求体必须是携带text字段的JSON对象,就算签名逻辑正确,这处错误也会导致接口返回400参数错误。
最简修正方案(推荐)
不需要手动集成Typhoeus,oauth gem本身已经封装了带自动签名的请求方法,代码更简洁也不需要额外适配,直接使用已有的access token发起请求即可,完全跳过PIN授权流程:
require 'oauth' require 'json' # 替换为你自己的有效凭证 consumer_key = 'YOUR_CONSUMER_KEY' consumer_secret = 'YOUR_CONSUMER_SECRET' access_token = 'YOUR_ACCESS_TOKEN' access_token_secret = 'YOUR_ACCESS_TOKEN_SECRET' consumer = OAuth::Consumer.new( consumer_key, consumer_secret, site: 'https://api.twitter.com' ) # 直接用已有token初始化,不需要走授权跳转、PIN校验流程 access_token_obj = OAuth::AccessToken.new(consumer, access_token, access_token_secret) # 构造符合接口要求的请求体 request_body = JSON.dump({ text: "Hello, world!" }) # 发起请求,gem自动完成OAuth1签名计算 response = access_token_obj.post( 'https://api.twitter.com/2/tweets', request_body, { 'User-Agent' => 'v2CreateTweetRuby', 'Content-Type' => 'application/json' } ) puts "响应状态码:#{response.code}" puts "响应内容:#{response.body}"
保留Typhoeus的修正方案
如果你需要使用Typhoeus的异步、并发等特性,不要将Typhoeus请求实例传入OAuth Helper,手动传入请求方法、URI等基础参数生成授权头即可:
require 'typhoeus' require 'oauth' require 'json' # 替换为你自己的有效凭证 consumer_key = 'YOUR_CONSUMER_KEY' consumer_secret = 'YOUR_CONSUMER_SECRET' access_token = 'YOUR_ACCESS_TOKEN' access_token_secret = 'YOUR_ACCESS_TOKEN_SECRET' create_tweet_url = "https://api.twitter.com/2/tweets" request_body = JSON.dump({ text: "Hello, world!" }) consumer = OAuth::Consumer.new(consumer_key, consumer_secret, site: 'https://api.twitter.com') token = OAuth::Token.new(access_token, access_token_secret) # 手动传入签名所需的基础参数,不依赖Typhoeus实例 oauth_helper = OAuth::Client::Helper.new( { method: :post, uri: create_tweet_url }, { consumer: consumer, token: token, request_uri: create_tweet_url } ) auth_header = oauth_helper.header request = Typhoeus::Request.new( create_tweet_url, method: :post, headers: { "User-Agent": "v2CreateTweetRuby", "Content-Type": "application/json", "Authorization": auth_header }, body: request_body ) response = request.run puts "响应状态码:#{response.code}" puts "响应内容:#{response.body}"
验证提示
- 你已经在Postman验证过凭证有效性,只要签名逻辑正确、请求格式符合要求即可正常调用接口
- 请确认你的应用已开启
tweet.read、tweet.write权限,否则签名正确也会返回403权限错误
内容的提问来源于stack exchange,提问作者lumiere
相关产品推荐
相关产品推荐

