使用Ruby获取推文返回“open_http”:400错误请求(OpenURI :: HTTPError)

时间:2016-02-16 14:01:22

标签: ruby twitter twitter-oauth

我是Ruby新手。我已经开始阅读 Bastards Book Ruby 的第一章,即Tweet fetching,但本教程使用的是Twitter API v1。我得到的回应告诉我使用v1.1。所以,我按照教程编写了一个程序:

require 'oauth'

def prepare_access_token(oauth_token, oauth_token_secret)
    consumer = OAuth::Consumer.new("apiKey", "APISecret", { :site => "https://api.twitter.com", :scheme => :header })

    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

access_token = prepare_access_token("AccessToken", "AccessTokenSecret")

response = access_token.request(:get, "https://api.twitter.com/1.1/statuses/home_timeline.json")
puts response 

输出:#<Net::HTTPOK:0x007fb7eb0885b8>

如果我在这里运行程序。它运行得很好。但是,如果我添加以下内容来获取推文并写入文件。我收到错误

twitter_user = "iAbhimanyuAryan"
remote_base_url = "https://api.twitter.com/1.1/statuses/user_timeline.json?count=100&screen_name="

remote_full_url = remote_base_url + twitter_user

tweets = open(remote_full_url).read

my_local_filename = twitter_user + "-tweets.json"

my_local_file = open(my_local_filename, "w")
      my_local_file.write(tweets)

my_local_file.close    

错误:

❯ ruby twitter.rb
#<Net::HTTPOK:0x007fbbfc9d75c8>
/Users/abhimanyuaryan/.rbenv/versions/2.2.3/lib/ruby/2.2.0/open-uri.rb:358:in `open_http': 400 Bad Request (OpenURI::HTTPError)
    from /Users/abhimanyuaryan/.rbenv/versions/2.2.3/lib/ruby/2.2.0/open-uri.rb:736:in `buffer_open'
    from /Users/abhimanyuaryan/.rbenv/versions/2.2.3/lib/ruby/2.2.0/open-uri.rb:211:in `block in open_loop'
    from /Users/abhimanyuaryan/.rbenv/versions/2.2.3/lib/ruby/2.2.0/open-uri.rb:209:in `catch'
    from /Users/abhimanyuaryan/.rbenv/versions/2.2.3/lib/ruby/2.2.0/open-uri.rb:209:in `open_loop'
    from /Users/abhimanyuaryan/.rbenv/versions/2.2.3/lib/ruby/2.2.0/open-uri.rb:150:in `open_uri'
    from /Users/abhimanyuaryan/.rbenv/versions/2.2.3/lib/ruby/2.2.0/open-uri.rb:716:in `open'
    from /Users/abhimanyuaryan/.rbenv/versions/2.2.3/lib/ruby/2.2.0/open-uri.rb:34:in `open'
    from twitter.rb:27:in `<main>'

1 个答案:

答案 0 :(得分:1)

查看man pages for the Twitter API,此请求需要身份验证。

您需要使用AccessToken对象发出请求。像这样:

# response is a [Net::HTTPResponse][3]
response = access_token.get(remote_full_url)

# Get the entire body of the response
tweets = response.body

注意,这是一种非常基本的方法。如果您将此类代码投入生产,则需要添加适当的检查和错误处理。