Monday, February 21, 2011

how to update twitter in rails

def post_to_twitter
message = from some where
url = URI.parse('http://twitter.com/statuses/update.xml')
req = Net::HTTP::Post.new(url.path)
req.basic_auth 'account', 'password'
req.set_form_data({'status' => message})
res = Net::HTTP.new(url.host, url.port).start {|http| http.request(req) }
case res
when Net::HTTPSuccess, Net::HTTPRedirection
  # ok
else
  # false
end

end

this is the code for the twitter update, It is always be false when I post some updates to twitter through this action.

Can I know where is wrong?

From stackoverflow
  • I advise you to use Twitter gem

    Using the API you you just have to do:

    httpauth = Twitter::HTTPAuth.new('username', 'password')
    client = Twitter::Base.new(httpauth)
    client.update('Heeeeyyyyooo from the Twitter Gem')
    

    And using OAuth(which I highly recommend):

    oauth = Twitter::OAuth.new('consumer token', 'consumer secret')
    oauth.authorize_from_access('access token', 'access secret')
    client = Twitter::Base.new(oauth)
    client.update('Heeeyyyyoooo from Twitter Gem!')
    

0 comments:

Post a Comment