现在,我从这个v2中获取了Twitter 链接 API的示例代码。这个示例代码展示了OAuth和是如何工作的。它可以很好地处理我的消费者密钥和消费者秘密。
我想把代码简化如下。它假设访问令牌和访问令牌秘密已经知道,它跳过用户批准的过程,比如提供提供PIN的URL。
require 'typhoeus'
require 'json'
consumer_key = CONSUMER_KEY
consumer_secret = CONSUMER_SECRET
token = ACCESS_TOKEN
token_secret = ACCESS_TOKEN_SECRET
consumer = OAuth::Consumer.new(consumer_key, consumer_secret, :site => 'https://api.twitter.com')
options = {
:method => :post,
headers: {
"User-Agent": "v2CreateTweetRuby",
"content-type": "application/json"
},
body: JSON.dump("Hello, world!")
}
create_tweet_url = "https://api.twitter.com/2/tweets"
request = Typhoeus::Request.new(create_tweet_url, options)
access_token = OAuth::Token.new(token, token_secret)
oauth_params = {:consumer => consumer, :token => access_token}
oauth_helper = OAuth::Client::Helper.new(request, oauth_params.merge(:request_uri => create_tweet_url))
request.options[:headers].merge!({"Authorization" => oauth_helper.header}) # Signs the request
response = request.run
puts response然后,我看到下面的错误消息。
ruby test_tweet.rb
/usr/local/lib/ruby/gems/3.1.0/gems/oauth-0.5.10/lib/oauth/request_proxy.rb:18:in `proxy': Typhoeus::Request (OAuth::RequestProxy::UnknownRequestType)
from /usr/local/lib/ruby/gems/3.1.0/gems/oauth-0.5.10/lib/oauth/signature.rb:12:in `build'
from /usr/local/lib/ruby/gems/3.1.0/gems/oauth-0.5.10/lib/oauth/signature.rb:23:in `sign'
from /usr/local/lib/ruby/gems/3.1.0/gems/oauth-0.5.10/lib/oauth/client/helper.rb:49:in `signature'
from /usr/local/lib/ruby/gems/3.1.0/gems/oauth-0.5.10/lib/oauth/client/helper.rb:82:in `header'
from test_tweet.rb:28:in `<main>'当我使用irb并一步一步地尝试时,这个错误会发生在oauth_helper.header。由于这是第一次使用OAuth API,我可能会犯一些容易犯的错误。有人发现我的代码有什么问题吗?
我确认了我的访问令牌和访问令牌秘密工作在https://web.postman.co/。
谢谢。
发布于 2022-08-01 22:49:55
你需要插入
require 'oauth/request_proxy/typhoeus_request'
你的代码可以完成你想要的任务。其他台词在我看来不错!
在oauth/request_proxy.rb中,oauth库检查请求对象的类。
return request if request.is_a?(OAuth::RequestProxy::Base)
klass = available_proxies[request.class]
# Search for possible superclass matches.
if klass.nil?
request_parent = available_proxies.keys.find { |rc| request.is_a?(rc) }
klass = available_proxies[request_parent]
end
raise UnknownRequestType, request.class.to_s unless klass通过要求'oauth/request_proxy/typhoeus_request',Typhoeus::Request可以继承OAuth::RequestProxy::Base并避免引发UnknownRequestType错误。
https://stackoverflow.com/questions/72926611
复制相似问题