Sinatra 搭建服务和使用 POST 和 GET 请求服务示例(简单但实用)

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

先安装 sinatra 模块:

gem install sinatra

服务端:

# server.rb

require 'sinatra'
 
configure do
  set :bind, 'localhost'
  set :port, '1234'
end
      
get '/get-test' do
  'get request success'
end

post '/post-test' do
  puts request.body.read
  'post request success'
end

 客户端:

# client.rb

require '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 Thin
2020-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 1024
2020-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.0168
aaa=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 success
post request success

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

gem install rest-client
# client.rb

require '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
# or
post_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.rb
get request success
get request success
post request success
post request success

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值