博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Sinatra 搭建服务和使用 POST 和 GET 请求服务示例(简单但实用)
阅读量:4229 次
发布时间:2019-05-26

本文共 2053 字,大约阅读时间需要 6 分钟。

Ruby 的 Sinatra 其实有点类似于 Python 的 Flask。我另外一篇博客也写了用 Flask 搭建服务和使用请求服务示例: 。都是用的最简单的例子,并不复杂。

先安装 sinatra 模块:

gem install sinatra

服务端:

# server.rbrequire 'sinatra' configure do  set :bind, 'localhost'  set :port, '1234'end      get '/get-test' do  'get request success'endpost '/post-test' do  puts request.body.read  'post request success'end

 客户端:

# client.rbrequire 'net/https'domain = "localhost"port = "1234"# get 请求http = Net::HTTP.new(domain, port)response = http.request_get('/get-test')puts response.body# post 请求post_data = { "aaa" => 1, "bbb" => 2 }uri = URI.parse("http://#{domain}:#{port}/post-test")response = Net::HTTP.post_form(uri, post_data)  puts response.body

服务端运行输出:

[root@master ruby_learning]# ruby server.rb == Sinatra (v2.1.0) has taken the stage on 1234 for development with backup from Thin2020-12-02 22:23:02 +0800 Thin web server (v1.8.0 codename Possessed Pickle)2020-12-02 22:23:02 +0800 Maximum connections set to 10242020-12-02 22:23:02 +0800 Listening on localhost:1234, CTRL+C to stop::1 - - [02/Dec/2020:22:23:09 +0800] "GET /get-test HTTP/1.1" 200 19 0.0168aaa=1&bbb=2::1 - - [02/Dec/2020:22:23:09 +0800] "POST /post-test HTTP/1.1" 200 20 0.0005

 客户端运行输出:

[root@master ruby_learning]# ruby client.rb get request successpost request success

当然,客户端如果只是发一下 get 和 post 请求的话,还有更简单的方法(rest-client 是个不错的选择):

gem install rest-client
# client.rbrequire 'rest-client'domain = "localhost"port = "1234"# get 请求response = RestClient.get("http://#{domain}:#{port}/get-test")puts response# or response = RestClient::Request.execute(  method: "get",  url: "http://#{domain}:#{port}/get-test")puts response# post 请求post_data = { "aaa" => 1, "bbb" => 2 }response = RestClient.post("http://#{domain}:#{port}/post-test", post_data)puts response# orpost_data = { "aaa" => 1, "bbb" => 2 }response = RestClient::Request.execute(  method: "post",  url: "http://#{domain}:#{port}/post-test",  payload: post_data)puts response
[root@master ruby_learning]# ruby client.rbget request successget request successpost request successpost request success

 

转载地址:http://nnjqi.baihongyu.com/

你可能感兴趣的文章
VC下线程同步的三种方法(互斥、事件、临界区)/(转)
查看>>
非常好的一篇U-BOOT的文章--转载
查看>>
【设计模式】学习之创建型 单例模式
查看>>
【设计模式】学习之创建型 原型模式
查看>>
【设计模式】学习之结构型 适配器模式-装饰器模式-代理模式
查看>>
Maven+Eclipse+Tomcat+Spring MVC web 请求 404 问题总结及noHandlerFound
查看>>
SpringMVC API缓存 LastModified的实现总结
查看>>
406 Not Acceptable 415 Unsupported Media Type Spring MVC consumes与produces
查看>>
MyBatis 高级映射与懒加载
查看>>
HCIP-H12-222练习题
查看>>
点到点IPSec VPN的配置
查看>>
MySQL InnoDB何时更新表的索引统计信息
查看>>
MTU 设置错误导致防火墙或者路由器断网
查看>>
子网划分详解与子网划分实例
查看>>
游戏通讯技术:帧同步技术
查看>>
防火墙技术指标---并发连接数/吞吐量
查看>>
V100服务器和T4服务器的性能指标
查看>>
elasticsearch 启动、停止及更改密码
查看>>
Kafka,它为什么速度会这么快?
查看>>
zookeeper安装启动的一些问题
查看>>