Net::HTTPでレオネットのパスワード認証プログラムを書いてみた
レオパレスに入居すると強制的にレオネットというブロードバンド(自称)のサービスを受けることになる。
やたら遅いうえに、何時間かおきにパスワードの認証を要求してくるのがもーイヤっ。
なので、Ruby の Net::HTTP というライブラリでユーザ認証するプログラムを書いてみた。
とりあえず認証方法が BASIC 認証みたいなのでこんな感じ。
require 'net/http'
Net::HTTP.version_1_2def fetch(userid, password)
req = Net::HTTP::Get.new('/index.html')
req.basic_auth(userid, password)
Net::HTTP.start('www.google.co.jp', 80) do |http|
res = http.request(req)
end
end
実行してみた。だめだ、307が返ってきた!307ってなんだけな。
StudyingHTTP:http://www.studyinghttp.net/status_code#Code307
そっか。じゃ302とかも返るのかな。
require 'net/http'
Net::HTTP.version_1_2def fetch(uri_str, userid, password)
uri = URI(uri_str)
req = Net::HTTP::Get.new(uri.path)
req.basic_auth(userid, password)
Net::HTTP.start(uri.host, 80) do |http|
res = http.request(req)
case res.code
when 200 then res
when 302 then fetch(res['Location'], userid ,password)
when 304 then fetch(res['Location'], userid ,password)
when 307 then fetch(res['Location'], userid ,password)
end
puts res.code
end
end
なんかかっちょ悪いなぁ・・笑
ここにきて一番参考になりそうな、るびまを拝見。
RubyistMagazine 標準添付ライブラリ紹介 【第 7 回】 net/http
http://jp.rubyist.net/magazine/?0013-BundledLibraries
まったく同じのを発見したので、そのまま拝借。
require 'net/http'
Net::HTTP.version_1_2def fetch(uri_str, userid, password)
uri = URI(uri_str)
req = Net::HTTP::Get.new(uri.path)
req.basic_auth(userid, password)
Net::HTTP.start(uri.host, 80) do |http|
res = http.request(req)
case res
when Net::HTTPSuccess then res
when Net::HTTPRedirection then fetch(res['Location'], userid ,password)
else
res.error!
end
puts res.code
end
endfetch('http://www.google.co.jp/index.html' , userid, password)
URI使ったからベタに'www.google.co.jp'なんて書くより読みやすくなった。
res.code もやめてレスポンスの継承関係で判定すると、HTTPのステータスコードなんて知らなくても直感で読めるようになるんだね。勉強になった◎
あとでお師匠に言ったら、「Mechanize でもできるよ」だって。
今度は会社のプロキシ認証のプログラムを Mechanize で実装しよっと。