本文共 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/