当前位置: 首页 > 工具软件 > Sinatra > 使用案例 >

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

子车成和
2023-12-01

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

 

 类似资料: