首先是介绍一下这个gem:oauth
项目首页是:http://oauth.rubyforge.org/,封装了Oauth的一些加密的过程和获取access token的过程,直接调用相应方法就可以了,里面也有例子可以参考。
这个Gem有一点问题还没有解决,比如微博需要上传文件,就不行咯。。。。大概原理是这样滴,这个gem会自动对传过去的所有参数进行签名,具体的签名方法请参考Oauth认证的详细说明……拿新浪微博举例子吧,需要一个status参数和一个pic参数,如果按照封装的方法传入这两个参数之后,会对status和pic参数进行签名,但是一般pic文件都是直接采用binary方式上传到服务器,并不需要签名。这样就无法用封装的方法了,遇到这种情况还是自己写吧。
下面是具体的方法,使用的时候直接调用upload_weibo就可以了~
CRLF = "\r\n"
#发布带图片的微博信息,因为Oauth这个gem暂时还不支持带图片参数的post请求
#所以自己构造请求的body部分,然后使用sign!这个方法来为请求的参数签名
def upload_weibo(req_path, consumer, access_token, status, file_path)
url = URI.parse(req_path)
Net::HTTP.new(url.host, url.port).start do |http|
req = Net::HTTP::Post.new(url.request_uri)
req.set_form_data({"status" => CGI.escape(status.to_s)})
add_oauth(req, consumer, access_token)
add_multipart_data(req, {:pic=> File.new(file_path, "rb"), :status=> status})
res = http.request(req)
res.body
end
end
private
#对请求主体进行签名,调用Oauth的sign!方法
#因为pic参数一般不进行签名,所以现在的请求主体不包含pic信息
#仅仅包含请求的微博文本信息
def add_oauth(req, consumer, access_token)
consumer.sign!(req, access_token)
end
#创建请求的body部分,包含所有的信息(文字信息,上传的图片)
def add_multipart_data(req, params)
boundary = Time.now.to_i.to_s(16)
req["Content-Type"] = "multipart/form-data; boundary=#{boundary}"
body = ""
params.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}#{CGI.escape(value.to_s)}"
end
body << CRLF
end
body << "--#{boundary}--#{CRLF*2}"
req.body = body
req["Content-Length"] = req.body.size
end
#检测文件的类型
#传入的参数是文件的路径信息,根据正则表达式判断为什么类型的文件
def mime_type(file)
case
when file =~ /\.jpg/ then 'image/jpg'
when file =~ /\.gif$/ then 'image/gif'
when file =~ /\.png$/ then 'image/png'
else 'application/octet-stream'
end
end