图片未在Twitter上发布

时间:2013-08-05 05:41:12

标签: ruby-on-rails ruby twitter

consumer_key=my_consumer_key
consumer_secret=my_consumer_secret
access_token=my_access_token
access_secret=my_access_secret

consumer = OAuth::Consumer.new(consumer_key,consumer_secret,{:site => "https://api.twitter.com",:scheme => :header,:authorize_path => '/oauth/authenticate'})
 token_hash = { :oauth_token =>access_token,:oauth_token_secret =>access_secret}

#access_token = OAuth::AccessToken.new(
 # consumer,
  #config['oauth_token'],
  #config['oauth_token_secret'])
 access_token = OAuth::AccessToken.from_hash(consumer, token_hash)
img = open("https://s3.amazonaws.com/fbappshq-assets/datas/7828/thumb.png")
#image_path = File.expand_path('https://s3.amazonaws.com/fbappshq-assets/datas/7828/thumb.png', File.dirname(__FILE__))
boundary = 'cce6735153bf14e47e999e68bb183e70a1fa7fc89722fc1efdf03a917340'
request_body = ''
request_body.concat("--#{boundary}\r\n")
request_body.concat("Content-Disposition: form-data; name=\"status\";\r\n")
request_body.concat("\r\n")
request_body.concat("#{Time.now.to_s}\r\n")
request_body.concat("--#{boundary}\r\n")
#request_body.concat("Content-Disposition: form-data; name=\"media[]\"; filename=\"#{File.basename(image_path)}\"\r\n")
request_body.concat("Content-Disposition: form-data; name=\"media[]\"; filename=\"#{img}\"\r\n")
#request_body.concat("Content-Type: application/x-www-form-urlencoded\r\n")
request_body.concat("Content-Type:multipart/form-data\r\n")
request_body.concat("Accept-Encoding:gzip\r\n")
request_body.concat("Content-Transfer-Encoding: binary\r\n")
request_body.concat("\r\n")
image_path='https://s3.amazonaws.com/fbappshq-assets/datas/7828/thumb.png'
open(image_path, 'rb') do |f|
  request_body.concat(f.read)
end
request_body.concat("\r\n")
request_body.concat("--#{boundary}--\r\n")

#uri = URI.parse('https://upload.twitter.com/1.1/statuses/update_with_media.json')
uri=URI.parse("https://api.twitter.com/1.1/statuses/update_with_media.json")
https = Net::HTTP.new(uri.host, uri.port)
https.use_ssl = true
https.start do |session|
  request = Net::HTTP::Post.new(uri.request_uri)
  request.set_content_type("multipart/form-data; boundary=#{boundary}")
   request.set_content_type("multipart/form-data")
  request.body = request_body
  request['Content-Length'] = request.body.bytesize
  a=access_token.sign!(request)
  b= session.request(request)
   puts "b---#{b.body}"
end

它给了我们

{"errors":[{"message":"Internal error","code":131}]}

我怎么解决这个问题请帮助我。

1 个答案:

答案 0 :(得分:2)

使用socialshare gem,您可以轻松地在facebook,twitter,linkedin上分享消息(文本,图片)..所以根据您的要求,您可以通过这种方式发布图片,

s = Socialshare::Tweeter.new(:consumer_key => TWITTER_CONSUMER_KEY, 
                    :consumer_secret => TWITTER_CONSUMER_SECRET,
                    :token => twitter_user_token, 
                    :secret => twitter_user_secret)

s.twitter_user.update_with_media("text", your_file_path)

所以这会将图片上传到twitter,你可以在这个gem here上获得更多信息。