本文簡要介紹ruby語言中 OpenURI模塊
的用法。
OpenURI
是 Net::HTTP
、 Net::HTTPS 和 Net::FTP 的 easy-to-use 包裝器。
示例
可以像打開文件一樣打開 http、https 或 ftp URL:
URI.open("http://www.ruby-lang.org/") {|f|
f.each_line {|line| p line}
}
打開的文件有幾個用於 meta-information 的 getter 方法,如下所示,因為它是由 OpenURI::Meta
擴展的。
URI.open("http://www.ruby-lang.org/en") {|f|
f.each_line {|line| p line}
p f.base_uri # <URI::HTTP:0x40e6ef2 URL:http://www.ruby-lang.org/en/>
p f.content_type # "text/html"
p f.charset # "iso-8859-1"
p f.content_encoding # []
p f.last_modified # Thu Dec 05 02:45:02 UTC 2002
}
額外的標頭字段可以由可選的散列參數指定。
URI.open("http://www.ruby-lang.org/en/",
"User-Agent" => "Ruby/#{RUBY_VERSION}",
"From" => "foo@bar.invalid",
"Referer" => "http://www.ruby-lang.org/") {|f|
# ...
}
http_proxy、https_proxy、ftp_proxy等環境變量默認生效。這裏我們禁用代理:
URI.open("http://www.ruby-lang.org/en/", :proxy => nil) {|f|
# ...
}
有關可用選項的更多信息,請參閱 OpenURI::OpenRead.open
和 URI.open
。
URI
對象可以用類似的方式打開。
uri = URI.parse("http://www.ruby-lang.org/en/")
uri.open {|f|
# ...
}
URI
對象可以直接讀取。返回的字符串也由 OpenURI::Meta
擴展。
str = uri.read
p str.base_uri
- 作者
-
Tanaka Akira <akr@m17n.org>
相關用法
- Ruby Open3.capture3用法及代碼示例
- Ruby Open3.capture2用法及代碼示例
- Ruby OpenStruct.ostruct[name] =用法及代碼示例
- Ruby OpenSSL.fips_mode =用法及代碼示例
- Ruby OpenSSL模塊用法及代碼示例
- Ruby Open3.capture2e用法及代碼示例
- Ruby Open3.popen2e用法及代碼示例
- Ruby OpenRead.open用法及代碼示例
- Ruby Open3.popen3用法及代碼示例
- Ruby Open3.popen2用法及代碼示例
- Ruby OpenSSL.print_mem_leaks用法及代碼示例
- Ruby Open3.pipeline用法及代碼示例
- Ruby Open3.pipeline_rw用法及代碼示例
- Ruby OpenStruct類用法及代碼示例
- Ruby OpenSSL.Digest用法及代碼示例
- Ruby OpenStruct.==用法及代碼示例
- Ruby OpenStruct.each_pair用法及代碼示例
- Ruby OpenStruct.delete_field用法及代碼示例
- Ruby OpenStruct.dig用法及代碼示例
- Ruby Open3.pipeline_w用法及代碼示例
- Ruby Open3.pipeline_r用法及代碼示例
- Ruby OpenStruct.new用法及代碼示例
- Ruby Open3.pipeline_start用法及代碼示例
- Ruby OpenStruct.ostruct[name]用法及代碼示例
- Ruby Option.level用法及代碼示例
注:本文由純淨天空篩選整理自ruby-lang.org大神的英文原創作品 OpenURI模塊。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。