Ruby RestClient.get 限制必须返回 Response 对象

linjunhalida · 2014年07月23日 · 最后由 linjunhalida 回复于 2014年07月23日 · 3961 次阅读

我现在在用 RestClient.get,资源是一个图片,按照文档,它会自动返回图片数据字符串。 但是问题是这个资源没有准备好的时候会返回 202,在这种情况下,我需要获得 header 信息。

请问有什么办法让 RestClient.get 必须返回 Response 对象?我看了源码,没有找到怎么只返回字符串的。。

资源没准备好是什么意思?是这个资源不存在?还是说这个资源是一个正在被写入的文件,但是写入了一半而已。

@Victor 这个资源正在生成中,服务器返回一个 202,以及 header 里面有等待时间。

文档的 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 的

#3 楼 @Victor 帮不到,RestClient.get 返回的是字符串,包在 block 里面返回的也是字符串,看了代码不知道哪里处理了,晕。。

我的意思是

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 到底做了什么。。

#8 楼 @Victor 知道有 code 就好办了,不过为什么 class 是 String?去翻源码。。

看明白了,在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。。

需要 登录 后方可回复, 如果你还没有账号请 注册新账号