【发布时间】:2016-09-17 14:35:39
【问题描述】:
这是我第一次使用 Twitter API 的经验。 我正在使用以下工具:
- ruby 2.2.0p0(2014-12-25 修订版 49005)[x86_64-linux]
-
宝石'oauth'
- oauth (0.5.1)
- oauth2 (1.1.0)
- omniauth-oauth2 (1.4.0)
我从 Twitter 获得了一个密钥和秘密。
我从example on Twitter for Ruby 复制并粘贴。
=begin
code taken directly from the example at
https://dev.twitter.com/oauth/overview/single-user
=end
require 'oauth'
consumer_key, \
consumer_secret = [
'CONSUMER_KEY',
'CONSUMER_SECRET'
].map { |key| ENV[key] }
raise "Some key undefined." unless [consumer_key, consumer_secret].all?
# Exchange your oauth_token and oauth_token_secret for an AccessToken instance.
def prepare_access_token(oauth_token, oauth_token_secret)
consumer = OAuth::Consumer.new("APIKey", "APISecret", { :site => "https://api.twitter.com", :scheme => :header })
# now create the access token object from passed values
token_hash = { :oauth_token => oauth_token, :oauth_token_secret => oauth_token_secret }
access_token = OAuth::AccessToken.from_hash(consumer, token_hash )
return access_token
end
# Exchange our oauth_token and oauth_token secret for the AccessToken instance.
access_token = prepare_access_token(consumer_key, consumer_secret)
p access_token
# use the access token as an agent to get the home timeline
response = access_token.request(:get, "https://api.twitter.com/1.1/statuses/home_timeline.json")
p response
=begin
|| #<OAuth::AccessToken:0x000000021ed938
@token="redacted", @secret="redacted",
@consumer=#<OAuth::Consumer:0x000000021edb68
@key="APIKey",
@secret="APISecret", @options={:signature_method=>"HMAC-SHA1",
:request_token_path=>"/oauth/request_token",
:authorize_path=>"/oauth/authorize",
:access_token_path=>"/oauth/access_token",
:proxy=>nil, :scheme=>:header,
:http_method=>:post, :oauth_version=>"1.0",
:site=>"https://api.twitter.com"}>,
@params={:oauth_token=>"redacted", :oauth_token_secret=>"redacted"}>
|| #<Net::HTTPUnauthorized 401 Authorization Required readbody=true>
=end
我尝试了什么:
-
获取新的密钥和秘密。
结果:
Net::HTTPUnauthorized 401 需要授权 readbody=true
同步了我的服务器时间,因为许多 Stack Overflow 帖子都提到如果服务器时间变化超过某个点,则会返回 401。我安装了ntp。
-
来自this list的建议
- 在 Twitter 设置中设置回调 URL:http://127.0.0.1:3000/auth/twitter/callback
-
API Console Tool 在推特上。使用我的 Twitter 帐户 https://api.twitter.com/1.1/statuses/home_timeline.json 进行身份验证后返回
HTTP/1.1 200 正常
连同预期数据。
感谢您提出从这里去哪里的建议。
UPDATE OAuth Tool on Twitter Developer 通过 curl 执行返回预期结果:
curl --get 'https://api.twitter.com/1.1/statuses/home_timeline.json' --header 'Authorization: OAuth oauth_consumer_key="redacted", oauth_nonce="redacted", oauth_signature="redacted", oauth_signature_method="HMAC-SHA1", oauth_timestamp="1463742270", oauth_token="redacted", oauth_version="1.0"' --verbose
返回预期的数据。
[{"created_at":"5 月 20 日星期五 11:05:21 +0000 2016","id":733614584754515968,"id_str":
"733614584754515968","text":"新手程序员应该具备的三个技能 学习 https://t。 co/1p9AxO5JPg 通过 @sitepointdotcom","截断":false,"entities":{"hashtags":[],"symbols" (截断)…
【问题讨论】:
标签: ruby oauth twitter-oauth