1. 建立HTTP连接(通过GET方式发送请求参数)   

require "open-uri"  
    #如果有GET请求参数直接写在URI地址中  
    uri = 'http://uri'
    html_response = nil  
    open(uri) do |http|  
      html_response = http.read  
    end  
    puts html_response

 

2. 通过POST发送请求参数

params = {}  
    params["name"] = 'Tom'  
    uri = URI.parse("http://uri")
    res = Net::HTTP.post_form(uri, params)   
    #返回的cookie  
    puts res.header['set-cookie']  
    #返回的html body  
    puts res.body

 

3.https-仅验证服务器

require 'net/https'
require 'uri'

uri = URI.parse('https://liuwm-pc:8081/2.html')

http = Net::HTTP.new(uri.host, uri.port)

http.use_ssl = true if uri.scheme == "https"  # enable SSL/TLS
http.verify_mode = OpenSSL::SSL::VERIFY_NONE #这个也很重要

http.start {
  http.request_get(uri.path) {|res|
    print res.body
  }
}

 

4.https-双向验证

开始一直找针对pfx的验证,但是google了半天也没找到。后来发现pfx也是pkcs12证书类型的一种,重新搜索关键词pkcs12,找到了自己想要的结果,汗一个~~

补充一下, ruby发送客户端时指定的是client.csr和client.key证书,而不是pfx(一直没找到), 效果上和浏览器指定pfx一样

 

require 'net/https'
require 'uri'

uri = URI.parse('https://liuwm-pc:8081/2.html')

http = Net::HTTP.new(uri.host, uri.port)

http.use_ssl = true if uri.scheme == "https"  # enable SSL/TLS
http.cert =OpenSSL::X509::Certificate.ne(File.read("D:/111/client.crt"))
http.key =OpenSSL::PKey::RSA.new((File.read("D:/111/client.key")), "123456")# key and password
http.verify_mode = OpenSSL::SSL::VERIFY_NONE #这个也很重要

http.start {
  http.request_get(uri.path) {|res|
    print res.body
  }
}

 

 

补充:Net::HTTP Cheat Sheet(手册)

挪威的ruby开发者August Lilleaas最近整理了一些关于如何使用 Net::HTTP库的代码示例
Net::HTTP被广泛的使用到许多库中,类似John Nunemaker’s的HTTParty和Paul DIx’s的高性能Typhoeus。作为标准库的一部分,Net::HTTP虽然没有简单好记的API,但也算是一个不错的可选方案。

这是连接: https://github.com/augustl/net-http-cheat-sheet , 可以直接download下来, 每个文件中都是相应的使用列子