我现在在用 RestClient.get,资源是一个图片,按照文档,它会自动返回图片数据字符串。 但是问题是这个资源没有准备好的时候会返回 202,在这种情况下,我需要获得 header 信息。
请问有什么办法让 RestClient.get 必须返回 Response 对象?我看了源码,没有找到怎么只返回字符串的。。
文档的 Result handling 部分能帮上忙吗?
# Don't raise exceptions but return the response
RestClient.get('http://example.com/resource'){|response, request, result| response }
➔ 404 Resource Not Found | text/html 282 bytes
# Manage a specific error code
RestClient.get('http://my-rest-service.com/resource'){ |response, request, result, &block|
case response.code
when 200
p "It worked !"
response
when 423
raise SomeCustomExceptionIfYouWant
else
response.return!(request, result, &block)
end
}
# Follow redirections for all request types and not only for get and head
# RFC : "If the 301, 302 or 307 status code is received in response to a request other than GET or HEAD,
# the user agent MUST NOT automatically redirect the request unless it can be confirmed by the user,
# since this might change the conditions under which the request was issued."
RestClient.get('http://my-rest-service.com/resource'){ |response, request, result, &block|
if [301, 302, 307].include? response.code
response.follow_redirection(request, result, &block)
else
response.return!(request, result, &block)
end
}
我猜想你的需求可能是,当这个资源还没有被生成完毕的时候,你想通过 RestClient.get 获取需要等待的时间。你说的是 response.code 返回 202。那 response 的其它部分应该也能正常拿到吧。毕竟 response 是一个完整的对象,没理由你只能获取 code 的
我的意思是
require 'pry'
RestClient.get('http://example.com/resource'){|response, request, result| binding.pry;response }
加个断点,把 response 打出来看看。
如果 response 是个字符串而不是对象。那就不知道咋办了
收到 so 的回复,检查了一下:
2.0.0-p451 :033 > s.class
=> String
2.0.0-p451 :034 > s.code
=> 200
2.0.0-p451 :035 > s.class
=> String
2.0.0-p451 :036 > s.headers
=> {:allow=>"GET, HEAD, OPTIONS", :content_length=>"269", :content_type=>"image/png", :date=>"Wed, 23 Jul 2014 08:54:00 GMT", :last_modified=>"Wed, 23 Jul 2014 08:52:01 GMT", :server=>"nginx", :vary=>"Accept", :connection=>"keep-alive"}
怎么是这种魔法??RestClient 到底做了什么。。
加完断点之后 response.class.included_modules 查看类包含的所有模块。找到这里
看明白了,在response.rb里面:
def self.create body, net_http_res, args
result = body || ''
result.extend Response
result.net_http_res = net_http_res
result.args = args
result
end
竟然是 extend body 来做的,难怪是 String。。