检查 Ruby HTTP 响应是否成功 [英] Check Ruby HTTP response for success

查看:47
本文介绍了检查 Ruby HTTP 响应是否成功的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何正确检查来自 Net::HTTP::Get 的响应(例如)成功"(即 2xx 返回码)?可悲的是,文档似乎对这个简单的问题保持沉默.

How does one properly check the response from Net::HTTP::Get (for example) for "success" (i.e., a 2xx return code)? The documentation seems to be sadly silent on this simple question.

我有:

response=Net::HTTP.new( host, port ).request my_get_request # details not important

经过一番谷歌搜索和近乎随机的输入后,我终于确定这是有效的:

After a bunch of Googling and near-random typing, I finally determined that this works:

response.class < Net::HTTPSuccess

这真的是规范的做法吗?

Is that actually the canonical way to do it?

推荐答案

对于Net::HTTP,是的,检查响应对象的类就是这样做的方法.使用 kind_of?(别名也为 is_a?) 更清晰一些(但在功能上等同于使用 <):

For Net::HTTP, yes, checking the class of the response object is the way to do it. Using kind_of? (aliased also as is_a?) is a bit clearer (but functionally equivalent to using <):

response.kind_of? Net::HTTPSuccess

调用 value on response 也将引发 Net::HTTPError 如果状态代码不是成功的(这是什么命名不当的方法……).

Calling value on response will also raise a Net::HTTPError if the status code was not a successful one (what a poorly named method…).

如果可以,您可能需要考虑使用 gem 代替 Net::HTTP,因为它们通常提供更好的 API 和性能.TyphoeusHTTParty 是两个不错的选择,等等.

If you can, you may want to consider using a gem instead of Net::HTTP, as they often offer better APIs and performance. Typhoeus and HTTParty are two good ones, among others.

这篇关于检查 Ruby HTTP 响应是否成功的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆