Rails Gem开发(三)——Typhoeus实现后台http请求

项目推进,需要实现在rails服务器后台通过http请求访问url来获取必要的信息。我们选择使用typhoeus来实现这一功能。
github:https://github.com/typhoeus/typhoeus

开发前需明确的问题


  • 我们需要实现怎样得功能?
  • Typhoeus 实现了怎样的功能?
  • Typhoeus 提供了哪些接口?

问题解决


需要实现的功能

我们需要通过在rails后台实现http请求,附带参数,请求后获得该http响应。例如我们有一个get携带参数请求,访问一个url后获得返回的参数。

Typhoeus 提供的功能

明确了我们的需求后,我们再来看看这个gem能为我们提供怎样的功能。

The primary interface for Typhoeus is comprised of three classes: Request, Response, and Hydra. Request represents an HTTP request object, response represents an HTTP response, and Hydra manages making parallel HTTP connections.

我们可以看到,typhoeus为我们提供了三个基本接口,分别是Request、Response和Hydra这三个类。其中Request对应http请求,response对应http相应,而hydra则产生并发http连接。根据我们的需求,我们暂时并不需要并发http连接,因而暂时不对Hydra进行了解,主要了解request和response这两个功能。

Typhoeus 提供的部分接口

  • Request接口
request = Typhoeus::Request.new(
    "www.example.com",
    method: :post,
    body: "this is a request body",
    params: { field1: "a field" },
    headers: { Accept: "text/html" }
)

第一个参数是一个url,之后的参数都是可选的,默认的:method方法是:get.
:params用来发送url参数,:body则是作为请求实体的(:body is for the request body)。

  • 请求运行
request.run
  • response
response = request.response
response.code
response.total_time
response.headers
response.body

response只有在请求运行后才能执行。
- 快速请求接口

Typhoeus.get("www.example.com")
Typhoeus.head("www.example.com")
Typhoeus.put("www.example.com/posts/1", body: "whoo, a body")
Typhoeus.patch("www.example.com/posts/1", body: "a new body")
Typhoeus.post("www.example.com/posts", body: { title: "test post", content: "this is my test"})
Typhoeus.delete("www.example.com/posts/1")Typhoeus.options("www.example.com")
  • 请求错误处理接口
request = Typhoeus::Request.new("www.example.com", followlocation: true)
request.on_complete do |response|
   if response.success?
     # hell yeah
   elsif response.timed_out?
     # aw hell no
     log("got a time out")
   elsif response.code == 0
     # Could not get an http response, something's wrong.
     log(response.return_message)
   else
     # Received a non-successful http response.
     log("HTTP request failed: " + response.code.to_s)
   end
end
request.run

除了这些接口,typhoeus还提供了很多接口,包括并行连接的Hydra接口,使用代理连接的接口,处理文件上传的接口等等,可以看出,typhoeus是一个功能很强大的gem,这里不对其它接口再进行详述,具体可以参见github.

typhoeus 实现流程


  • 安装typhoeus
gem "typhoeus"
  • 调用Request
request = Typhoeus::Request.new(url)
  • 运行request
request.run
  • 获得响应response
response = request.response
  • 获得响应中的信息
response.code
response.total_time
response.headers
response.body

总结


typhoeus是一个功能强大而且很方便的处理http连接的gem,实现后台http请求也是很方便的。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值