如何在ruby中用http 发送get,post请求

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

     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

  }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值