Class: TempmailSdk::Http::Response
- Inherits:
-
Object
- Object
- TempmailSdk::Http::Response
- Defined in:
- lib/tempmail_sdk/http.rb
Overview
HTTP 响应的轻量封装,统一暴露状态码/正文/JSON/cookie 等
Instance Attribute Summary collapse
-
#body ⇒ String
readonly
响应正文.
-
#raw ⇒ Net::HTTPResponse
readonly
原始响应对象.
-
#status_code ⇒ Integer
readonly
HTTP 状态码.
Instance Method Summary collapse
-
#cookie_value(name) ⇒ String?
从 Set-Cookie 中提取指定名称的 cookie 值.
-
#header(name) ⇒ String?
获取单个响应头(大小写不敏感).
-
#initialize(raw) ⇒ Response
constructor
A new instance of Response.
-
#json ⇒ Object
解析 JSON 正文.
-
#ok? ⇒ Boolean
状态码是否 2xx.
-
#raise_for_status ⇒ Object
状态码非 2xx 时抛出异常(错误消息含状态码,便于重试判定).
-
#set_cookies ⇒ Array<String>
获取全部 Set-Cookie 头.
Constructor Details
#initialize(raw) ⇒ Response
Returns a new instance of Response.
22 23 24 25 26 |
# File 'lib/tempmail_sdk/http.rb', line 22 def initialize(raw) @raw = raw @status_code = raw.code.to_i @body = raw.body || "" end |
Instance Attribute Details
#body ⇒ String (readonly)
Returns 响应正文.
18 19 20 |
# File 'lib/tempmail_sdk/http.rb', line 18 def body @body end |
#raw ⇒ Net::HTTPResponse (readonly)
Returns 原始响应对象.
20 21 22 |
# File 'lib/tempmail_sdk/http.rb', line 20 def raw @raw end |
#status_code ⇒ Integer (readonly)
Returns HTTP 状态码.
16 17 18 |
# File 'lib/tempmail_sdk/http.rb', line 16 def status_code @status_code end |
Instance Method Details
#cookie_value(name) ⇒ String?
从 Set-Cookie 中提取指定名称的 cookie 值
62 63 64 65 66 67 68 69 |
# File 'lib/tempmail_sdk/http.rb', line 62 def (name) .each do |line| line.split(";").first.to_s.strip.split("=", 2).then do |k, v| return v if k == name end end nil end |
#header(name) ⇒ String?
获取单个响应头(大小写不敏感)
49 50 51 |
# File 'lib/tempmail_sdk/http.rb', line 49 def header(name) @raw[name] end |
#json ⇒ Object
解析 JSON 正文
42 43 44 |
# File 'lib/tempmail_sdk/http.rb', line 42 def json JSON.parse(@body) end |
#ok? ⇒ Boolean
Returns 状态码是否 2xx.
29 30 31 |
# File 'lib/tempmail_sdk/http.rb', line 29 def ok? @status_code >= 200 && @status_code < 300 end |
#raise_for_status ⇒ Object
状态码非 2xx 时抛出异常(错误消息含状态码,便于重试判定)
34 35 36 37 38 |
# File 'lib/tempmail_sdk/http.rb', line 34 def raise_for_status return self if ok? raise "HTTP request failed: #{@status_code}" end |
#set_cookies ⇒ Array<String>
获取全部 Set-Cookie 头
55 56 57 |
# File 'lib/tempmail_sdk/http.rb', line 55 def @raw.get_fields("set-cookie") || [] end |