Ruby發送http協議(get、post、https服務器驗證、https雙向驗證)


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下來, 每個文件中都是相應的使用列子


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM