新手问题 关于 TwitterAPI:/1.1/statuses/update_with_media.json

w353284782 · October 23, 2012 · Last by liluo replied at October 23, 2012 · 3634 hits

小弟最近有需求是需要向 Twitter 上发布推文中包含图片, 看了下这个 Twitter 的 https://api.twitter.com/1.1/statuses/update_with_media.json 这个 API 能满足要求。 但是它上传的应该是一个二进制的流,这块又不是很懂,不知道从哪下手,不知道 各位大哥有没有什么插件能满足或者有例子就更好了!

这是之前写的新浪微博的版本

def build_and_post_multipart_bodies(faraday, url, parts)
  boundary = Time.now.to_i.to_s(16)
  body = ""
  parts.each do |key, value|
    esc_key = CGI.escape(key.to_s)
    body << "--#{boundary}#{CRLF}"
    if value.respond_to?(:read)
      body << "Content-Disposition: form-data; name=\"#{esc_key}\"; filename=\"#{File.basename(value.path)}\"#{CRLF}"
      body << "Content-Type: #{mime_type(value.path)}#{CRLF*2}"
      body << value.read
    else
      body << "Content-Disposition: form-data; name=\"#{esc_key}\"#{CRLF*2}#{value}"
    end
    body << CRLF
  end
  body << "--#{boundary}--#{CRLF*2}"
  response = faraday.post do |req|
    req.url url
    req.headers['Content-Type'] = "multipart/form-data; boundary=#{ boundary }"
    req.body = body
  end
end

不知道对你有没有用

#1 楼 @fresh_fish 我先试试 谢谢拉!

当初我写 @QiubaiBot 的时候,有人告诉我这么一句话:把图片内容 base64 后作为 media_data[] 参数上传即可。

You need to Sign in before reply, if you don't have an account, please Sign up first.