To obtain the content of an HTTP/FTP address in Ruby, you can easily use the open-Uri library.
Open-Uri library is included in Ruby's standard additional library, path: lib/oepn-uri.rb
After referencing this additional library, you can open the resource of an HTTP/ftp uri just like opening a common file.
The difference is as follows: Require ' Open-Uri '
Open ( ' C:/boot. ini ' ){ | File |
Puts file. Class # File
}
Open ( ' Http://coderlee.cnblogs.com ' ){ | File |
Puts file. Class # Tempfile
}
It can be seen that the block parameter for opening a local file is of the file type, while the block parameter for opening a URI is of the tempfile type.
Note that the open method in Open-Uri will automatically track access to the 302 redirection address, while the net: HTTP # Get method will not automatically track the 302 redirection address.
the final value returned by the function is the final value of the passed Code block. You can obtain the URI content data = open ( ' http://coderlee.cnblogs.com ' ) { | F | F. read
data = open ( ' http://coderlee.cnblogs.com ' ) { | F | F }. open. read
the reason for the second open statement is that the stream returned by the open method is a closed tempfile. Therefore, open the stream first, return the opened stream, and then call read to read the stream.