読者です 読者をやめる 読者になる 読者になる

( ꒪⌓꒪) ゆるよろ日記

( ゚∀゚)o彡°オパーイ!オパーイ! ( ;゚皿゚)ノシΣ フィンギィィーーッ!!!

Rubyのnet/http でHTTPリクエスト/レスポンスをdumpする方法

俺得メモ。もう3回くらい同じこと調べたんでいい加減メモ残しておく。


Net::HTTP にset_debug_outputってメソッドがあってコイツに出力先を渡せばいい。残念ながらこのset_debug_outputはドキュメントには載ってないのでnet/httpのソース見てね。

require 'net/http'
Net::HTTP.version_1_2

http = Net::HTTP.new("d.hatena.ne.jp", 80)
http.set_debug_output $stderr
http.start{|http|
  req = Net::HTTP::Get.new('/yuroyoro')
  res = http.request(req)
  print res.body
}

irbでやると

irb(main):001:0> require 'net/http'
=> true
irb(main):002:0> Net::HTTP.version_1_2
=> true
irb(main):003:0> http = Net::HTTP.new("d.hatena.ne.jp", 80)
=> #<Net::HTTP d.hatena.ne.jp:80 open=false>
irb(main):004:0> http.set_debug_output $stderr
=> #<IO:0x100177b80>
irb(main):005:0> http.start{|http|
irb(main):006:1*   req = Net::HTTP::Get.new('/yuroyoro')
irb(main):007:1>   res = http.request(req)
irb(main):008:1>   print res.body
irb(main):009:1> }
opening connection to d.hatena.ne.jp...
opened
<- "GET /yuroyoro HTTP/1.1\r\nAccept: */*\r\nHost: d.hatena.ne.jp\r\n\r\n"
-> "HTTP/1.1 302 Moved\r\n"
-> "Date: Mon, 16 May 2011 05:24:51 GMT\r\n"
-> "Server: Apache\r\n"
-> "X-Server: diarybackend96\r\n"
-> "X-Server: diarybackend96\r\n"
-> "Location: http://d.hatena.ne.jp/yuroyoro/\r\n"
-> "Content-Type: text/plain\r\n"
-> "Set-Cookie: b=$1$81unIXlP$t0N3q4P33OCLo/mjd6Phs/; path=/; expires=Sun, 11-May-31 05:24:51 GMT; domain=.hatena.ne.jp\r\n"
-> "Vary: Accept-Encoding,User-Agent\r\n"
-> "Transfer-Encoding: chunked\r\n"
-> "\r\n"
-> "142\r\n"
reading 322 bytes...
-> "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\n<HTML><HEAD>\n<TITLE>302 Moved</TITLE>\n</HEAD><BODY>\n<H1>Moved</H1>\nThe document has moved <A HREF=\"http://d.hatena.ne.jp/yuroyoro/\">here</A>.<P>\n<P>Additionally, a 302 Found\nerror was encountered while trying to use an ErrorDocument to handle the request.\n</BODY></HTML>\n"
read 322 bytes
reading 2 bytes...
-> "\r\n"
read 2 bytes
-> "0\r\n"
-> "\r\n"
Conn keep-alive
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<HTML><HEAD>
<TITLE>302 Moved</TITLE>
</HEAD><BODY>
<H1>Moved</H1>
The document has moved <A HREF="http://d.hatena.ne.jp/yuroyoro/">here</A>.<P>
<P>Additionally, a 302 Found
error was encountered while trying to use an ErrorDocument to handle the request.
</BODY></HTML>
=> nil


例えば、RailsActiveResourceなんか使ってて、ちょっとダンプ出したい時なんかはこんなモンキーパッチを当ててやればよい。

module ActiveResource
  class Connection                                                                                                                                                                                            
          
    alias_method :http_org, :http
          
    private 
      def http 
        net_http = http_org
        net_http.set_debug_output $stderr                                                            
        net_http
      end 
            
  end     
end