http模拟登录

= =其实很简单,写这个的目的呢,是为了练习下Ruby而已

就是post到登录地址,得到cookie,然后以后的请求都用这个cookie就好了。

 1 require 'net/http'
 2 module EasyHTTP
 3     class HTTP
 4         def initialize(url)
 5             @url = url
 6             @cookie = nil
 7         end
 8         def login
 9             uri =  URI.parse(@url)
10             params = {}
11             params['user.username'] = '[email protected]'
12             params['user.password'] = 'xxxx'
13             res = Net::HTTP.post_form(uri , params)
14             @cookie = res.header['set-cookie'].split('; ')[0]
15         end
16         def get(url)
17             login unless @cookie
18             uri = URI.parse(url)
19             http = Net::HTTP.new(uri.host , uri.port)
20             request = Net::HTTP::Get.new(uri.path)
21             request['Cookie'] = @cookie
22             res = http.request(request)
23             res.body
24         end
25     end
26 end
27 
28 sample = EasyHTTP::HTTP.new("http://loginAction url")
29 puts sample.get("http://some url u want")

 

你可能感兴趣的:(http)