分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > IT知识

ruby net/http模块使用

发布时间:2023-09-06 01:52责任编辑:白小东关键词:http


ruby中的NET::HTTP方法不支持持久连接,如果您执行许多HTTP请求,则不推荐它们;这里暂时先列出几个固定用法(用来还是有点不舒服的):

其中一,二不支持请求头设置(header取ruby默认值),只能用于基本的请求;三,四可以设置请求头;

NET::HTTP不能处理重定向和404 ;不支持会话保持

一. 基本GET请求get_response

require ‘net/http‘# 基本GET请求require ‘net/http‘uri = URI(‘http://httpbin.org/get‘)response = Net::HTTP.get_response(uri)puts response.body# 带参数的GET请求require ‘net/http‘uri = URI(‘http://httpbin.org/get?name=zhaofan&age=23‘)response = Net::HTTP.get_response(uri)puts response.body# 如果我们想要在URL查询字符串传递数据,通常我们会通过httpbin.org/get?key=val方式传递# URI模块允许使用 encode_www_form 方法,将一个HASH来进行转化,例子如下:require ‘net/http‘uri = URI(‘http://httpbin.org/get?‘)data = {name:‘zhaofan‘, age:23}uri.query = URI.encode_www_form(data)response = Net::HTTP.get_response(uri)puts response.body

二.基本post请求post_form(header默认为application/x-www-form-urlencoded)

require ‘net/http‘# 基本POST请求# 通过在发送post请求时添加一个params参数,这个params参数可以通过字典构造成;# 该方法底层和get_response一样都是调用了response方法uri = URI(‘http://httpbin.org/post‘)params = {name:‘zhaofan‘, age:23}res = Net::HTTP.post_form(uri, params)puts res.body

三.get固定用法

require ‘net/http‘url = URI(‘http://httpbin.org/get?‘)# 设置请求参数params = {‘name‘:‘test‘}url.query = URI.encode_www_form(params)http = Net::HTTP.new(url.host, url.port)# 设置请求头header = {‘user-agent‘:‘Chrome/61.0.3163.100‘}response = http.get(url, header)puts response.body

四.post固定用法

  • application/json
    require ‘net/http‘require ‘json‘#application/jsonurl = URI(‘http://httpbin.org/post‘)http = Net::HTTP.new(url.host, url.port)# 设置请求参数data = {‘code‘:1, ‘sex‘:‘男‘, ‘id‘:1900, ‘name‘: ‘test‘}.to_json# 设置请求头header = {‘content-type‘:‘application/json‘}response = http.post(url, data, header)puts response.body
  • application/x-www-form-urlencoded
    require ‘net/http‘require ‘json‘#application/x-www-form-urlencodedurl = URI(‘http://httpbin.org/post‘)http = Net::HTTP.new(url.host, url.port)#encodeURI参数data = URI.encode_www_form({‘name‘:‘test‘})#设置请求头header = {‘content-type‘:‘application/x-www-form-urlencoded‘}response = http.post(url, data,header)puts response.body

 五.response响应内容

require ‘net/http‘uri = URI(‘http://www.baidu.com‘)response = Net::HTTP.get_response(uri)puts "http版本:#{response.http_version}" #=> 1.1puts "响应代码: #{response.code}" #=> 200puts "响应信息:#{response.message}" #=> okputs "uri:#{response.uri}" #=> http://www.baidu.computs "解码信息:#{response.decode_content}" #=> trueputs response.body #=> 响应体response.header.each do |k,v| ?puts "#{k}:#{v}"end #=> 响应头

六.发送https请求

require ‘net/https‘# 设置httpshttp.use_ssl = truehttp.verify_mode = OpenSSL::SSL::VERIFY_NONE

ruby net/http模块使用

原文地址:https://www.cnblogs.com/wf0117/p/9000443.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved