zoukankan      html  css  js  c++  java
  • ruby URI类

    一. URI

    require 'uri'
    
    uri = URI("http://foo.com/posts?id=30&limit=5#time=1305298413")
    #=> #<URI::HTTP:0x00000000b14880
          URL:http://foo.com/posts?id=30&limit=5#time=1305298413>
    uri.scheme
    #=> "http"
    uri.host
    #=> "foo.com"
    uri.path
    #=> "/posts"
    uri.query
    #=> "id=30&limit=5"
    uri.fragment
    #=> "time=1305298413"
    
    uri.to_s
    #=> "http://foo.com/posts?id=30&limit=5#time=1305298413"

    二. 常用方法

    • encode_www_form(enum, enc=nil)

    URI.encode_www_form([["q", "ruby"], ["lang", "en"]])
    #=> "q=ruby&lang=en"
    URI.encode_www_form("q" => "ruby", "lang" => "en")
    #=> "q=ruby&lang=en"
    URI.encode_www_form("q" => ["ruby", "perl"], "lang" => "en")
    #=> "q=ruby&q=perl&lang=en"
    URI.encode_www_form([["q", "ruby"], ["q", "perl"], ["lang", "en"]])
    #=> "q=ruby&q=perl&lang=en"
    • decode_www_form(str, enc=Encoding::UTF_8, separator: '&', use__charset_: false, isindex: false)

    ary = URI.decode_www_form("a=1&a=2&b=3")
    p ary                  #=> [['a', '1'], ['a', '2'], ['b', '3']]
    p ary.assoc('a').last  #=> '1'
    p ary.assoc('b').last  #=> '3'
    p ary.rassoc('a').last #=> '2'
    p Hash[ary]            # => {"a"=>"2", "b"=>"3"}

    相当于对请求字符串进行编解码

    • URI.encode(str[, unsafe])
      URI.escape(str[, unsafe])

    require 'uri'
    p URI.encode('http://www.ruby-lang.org/ja/man-1.6/?cmd=view;name=Ruby参考手册')
    #=> http://www.ruby-lang.org/ja/man-1.6/?cmd=view;name=Ruby%B2%CE%BF%BC%CA%D6%B2%E1

    编码为URI字符串后返回结果

    • URI.unescape(str)
      URI.decode(str)

    require 'uri'
    p URI.unescape('http://www.ruby-lang.org/ja/man-1.6/?cmd=view;name=Ruby%B2%CE%BF%BC%CA%D6%B2%E1')
    #=> http://www.ruby-lang.org/ja/man-1.6/?cmd=view;name=Ruby参考手册

    解码URI字符串后返回结果

  • 相关阅读:
    AMQP 介绍
    JMS 介绍
    SpringCloud 入门实战(12)--Zipkin(2)--安装使用
    SpringCloud 入门实战(11)--Zipkin(1)--简介
    Kafka 入门实战(3)--SpringBoot 整合 Kafka
    跨域访问方法介绍(9)--nginx 反向代理
    跨域访问方法介绍(8)--使用 WebSocket
    个人网站建好啦!
    Spring Boot配置Slf4j + log4j2
    SpringBoot 解决跨域,3种解决方案
  • 原文地址:https://www.cnblogs.com/wf0117/p/8856429.html
Copyright © 2011-2022 走看看