Ruby openURI

2017-08-13  本文已影响0人  难道_fa74

像打开普通文件那样打开http/ftp的URL

open("http://www.ruby-lang.org/") {|f|
  f.each_line {|line| p line}
}

打开的文件对象已经被OpenURI::Meta所扩展, 您可以方便地获取meta信息

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
}

使用哈希表参数,您就可以指定添加的头字段

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以及ftp_proxy这些环境变量都是有效的. 若想禁用代理,可以这样 :proxy => nil

open("http://www.ruby-lang.org/en/raa.html",
  :proxy => nil) {|f|
  ...
}

URI对象的打开方式也是类似的

uri = URI.parse("http://www.ruby-lang.org/en/")
uri.open {|f|
  ...
} 

可以直接读取URI对象。返回的字符串已经被OpenURI::Meta所扩展

str = uri.read
p str.base_uri

访问https请求,open-uri + OpenSSL

request_uri=URI.parse('myurl')
request_uri.query=URI.encode_www_form params
output = open(request_uri, {ssl_verify_mode:OpenSSL::SSL::VERIFY_NONE})
obj = JSON.parse output.readlines.join("")

ruby发送https请求示例

require 'net/http'
require 'json'
require 'openssl'
#url = URI.parse('https://github.com')
url = URI.parse('https://localhost:3000')
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true if url.scheme == 'https'
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
req = Net::HTTP::Post.new('/', {'Content-Type' => 'application/json'})
req.body = JSON[{"name" => {"xx" => "xx","tt" => "yy"},"age" => "2"}]
puts req.body
puts http.request(req).body
上一篇下一篇

猜你喜欢

热点阅读