中关村村草 发表于 2011-03-14 10:50

Ruby如何用Oauth与第三方网站互动

转:hot88zh

Ruby如何用Oauth与第三方网站互动




首先是介绍一下这个gem:oauth

项目首页是:http://oauth.rubyforge.org/,封装了Oauth的一些加密的过程和获取access token的过程,直接调用相应方法就可以了,里面也有例子可以参考。


这个Gem有一点问题还没有解决,比如微博需要上传文件,就不行咯。。。。大概原理是这样滴,这个gem会自动对传过去的所有参数进行签名,具体的签名方法请参考Oauth认证的详细说明……拿新浪微博举例子吧,需要一个status参数和一个pic参数,如果按照封装的方法传入这两个参数之后,会对status和pic参数进行签名,但是一般pic文件都是直接采用binary方式上传到服务器,并不需要签名。这样就无法用封装的方法了,遇到这种情况还是自己写吧。


下面是具体的方法,使用的时候直接调用upload_weibo就可以了~


Ruby代码1.CRLF = "\r\n"
2.#发布带图片的微博信息,因为Oauth这个gem暂时还不支持带图片参数的post请求   
3.#所以自己构造请求的body部分,然后使用sign!这个方法来为请求的参数签名   
4.def upload_weibo(req_path, consumer, access_token, status, file_path)   
5.    url = URI.parse(req_path)   
6.    Net::HTTP.new(url.host, url.port).start do |http|   
7.      req = Net::HTTP::Post.new(url.request_uri)   
8.      req.set_form_data({"status" => CGI.escape(status.to_s)})   
9.      add_oauth(req, consumer, access_token)   
10.      add_multipart_data(req, {:pic=> File.new(file_path, "rb"), :status=> status})   
11.      res = http.request(req)   
12.      res.body   
13.    end
14.end
15.
16.
17.private   
18.
19.#对请求主体进行签名,调用Oauth的sign!方法   
20.#因为pic参数一般不进行签名,所以现在的请求主体不包含pic信息   
21.#仅仅包含请求的微博文本信息   
22.def add_oauth(req, consumer, access_token)   
23.    consumer.sign!(req, access_token)   
24.end
25.
26.#创建请求的body部分,包含所有的信息(文字信息,上传的图片)   
27.def add_multipart_data(req, params)   
28.    boundary = Time.now.to_i.to_s(16)   
29.    req["Content-Type"] = "multipart/form-data; boundary=#{boundary}"
30.    body = ""
31.    params.each do |key,value|   
32.      esc_key = CGI.escape(key.to_s)   
33.      body << "--#{boundary}#{CRLF}"
34.      if value.respond_to?(:read)   
35.      body << "Content-Disposition: form-data; name=\"#{esc_key}\"; filename=\"#{File.basename(value.path)}\"#{CRLF}"
36.      body << "Content-Type: #{mime_type(value.path)}#{CRLF*2}"
37.      body << value.read   
38.      else
39.      body << "Content-Disposition: form-data; name=\"#{esc_key}\"#{CRLF*2}#{CGI.escape(value.to_s)}"
40.      end
41.      body << CRLF   
42.    end
43.    body << "--#{boundary}--#{CRLF*2}"
44.    req.body = body   
45.    req["Content-Length"] = req.body.size   
46.end
47.
48.#检测文件的类型   
49.#传入的参数是文件的路径信息,根据正则表达式判断为什么类型的文件   
50.def mime_type(file)   
51.    case
52.    when file =~ /\.jpg/ then 'image/jpg'
53.    when file =~ /\.gif$/ then 'image/gif'
54.    when file =~ /\.png$/ then 'image/png'
55.    else 'application/octet-stream'
56.    end
57.end
页: [1]
查看完整版本: Ruby如何用Oauth与第三方网站互动