Authentication Error while using Twitter API upload_with_media.json in Ruby


#1

Hi All,

I am trying to post an Image using Twitter API upload_with_media.json in ruby.
But while doing so, I am getting this as the Error Message:

Net::HTTPUnauthorized:0x00003605c93278 response.code: 401

This is the Code I am trying for Authentication:

oauth_key = {
                 :consumer_key    => 'g0uxjlIYCyOHA', 
                 :consumer_secret => 'XXXXXX',
                 :access_key      => '2711184-rZePpS8eAV6zJRIB0',
                 :access_secret   => 'xxxxxxxx',
            }

tweet_text = "Test Tweet #{Time.now}"
twitterUpdateXMLURL = "https://api.twitter.com/1.1/statuses/update_with_media.json"
oauth_header = ROAuth.header(oauth_key, twitterUpdateXMLURL, { 'status'=>URI.escape(tweet_text, /[^a-zA-Z0-9\-\.\_\~]/) }, :post)
oauth_header_params = { 'Authorization' => oauth_header, "Content-Type" => "multipart/form-data" }

uri = URI.parse(twitterUpdateXMLURL)
http = Net::HTTP.new(uri.host, uri.port)
request = Net::HTTP::Post.new(uri.request_uri, oauth_header_params)
file = "./images/logo.jpg"

post_body = {}
post_body['status'] = tweet_text
post_body['media[]'] = File.read(file)

request.body = URI.encode_www_form(post_body)

response = http.request(request)

Can someone please suggest what Can be done to resolve this 401 Authentication Issue ?

Thanks,


#2

Can someone please provide some pointer to resolve this ?


#3

Hi, Now I made few code changes and now this is the code which i am trying to execute.

post_body = [] uri = URI.parse(twitterUpdateXMLURL) # Create the HTTP objects http = Net::HTTP.new(uri.host, uri.port) request = Net::HTTP::Post.new(uri.request_uri, header_params)

Add the file Data

post_body << "--#{BOUNDARY}\r\n"
post_body << "Content-Disposition: form-data; name=\"media\"; filename=\"#{File.basename(file)}\"\r\n"
post_body << "Content-Type: \"image/jpeg\"\r\n\r\n"
post_body << File.read(file)

post_body << “\r\n\r\n–#{BOUNDARY}–\r\n”

Add the JSON

post_body << "--#{BOUNDARY}\r\n"
post_body << "Content-Disposition: form-data; name=\"status\"\r\n\r\n"
post_body << tweet_text
post_body << "\r\n\r\n--#{BOUNDARY}--\r\n"

request.body = post_body.join

if uri.scheme == 'https’
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
end

Send the request

response = http.request(request)

While doing so, I am able to publish the media but the text is not getting tweeted. Can someone please suggest what can be done to make this work ?