Ruby发送http协议(get、post、https服务器验证、https双向验证)
1. 建立HTTP连接(通过GET方式发送请求参数)
require "open-uri"
#如果有GET请求参数直接写在URI地址中
html_response = nil
open(uri) do |http|
html_response = http.read
end
puts html_response
uri = URI("http://#{$serverIp}:80/3dwarehouse/save.do?createTime=#{createTime}&remark=#{remark}&creator=#{$username}&fname=#{pathName}&fsize=#{filesize}")
p uri
response = Net::HTTP.get_response(uri)
p response.body #获取body信息
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
}
}