现在我从这个链接中获取了一个Twitter v2 API的示例代码。这个示例代码展示了OAuth和twitter v2 API是如何发布tweet的。它可以很好地使用我的消费者密钥和消费者秘密。
我想把代码简化如下。它假设访问令牌和访问令牌的秘密已经被跳过用户批准的过程,如提供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/。
谢谢。
你需要插入
require 'oauth/request_proxy/typhoeus_request'
和你的代码可以完成你想要的任务。我觉得其他台词不错!
在oauth/request_proxy.rb
中,oauth库检查请求对象的类
https://github.com/oauth-xx/oauth-ruby/blob/master/lib/oauth/request_proxy.rb
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://github.com/oauth-xx/oauth-ruby/blob/master/lib/oauth/request_proxy/typhoeus_request.rb