我试图使用rest-client gem访问一些网站,我发现了一个让我感到困惑的行为。这与在一个糟糕的网站上使用rest-client有关,在本例中是www.google.com/this_does_not_exist。
我的期望:代码将运行且响应对象将有404响应代码。
实际发生了什么:有一个例外,代码提前终止。
当我尝试使用Net :: HTTP库时,我确实得到了预期的结果。
问题是:这种行为是否应该在rest-client中出现?如果是这样,在使用不良网站时,如何使用404响应代码取回对象。
以下是我的irb代码:
2.2.1 :045 > uri = URI('http://www.google.com')
=> #<URI::HTTP http://www.google.com>
2.2.1 :046 > response = Net::HTTP.get_response(uri)
=> #<Net::HTTPOK 200 OK readbody=true>
2.2.1 :047 > response.code
=> "200"
2.2.1 :048 > uri = URI('http://www.google.com/this_does_not_exist')
=> #<URI::HTTP http://www.google.com/this_does_not_exist>
2.2.1 :049 > response = Net::HTTP.get_response(uri)
=> #<Net::HTTPNotFound 404 Not Found readbody=true>
2.2.1 :050 > response.code
=> "404"
2.2.1 :051 > uri = URI('http://www.google.com')
=> #<URI::HTTP http://www.google.com>
2.2.1 :052 > response = RestClient.get('http://www.google.com')
=> <RestClient::Response 200 "<!doctype h...">
2.2.1 :053 > response.code
=> 200
2.2.1 :054 > response = RestClient.get('http://www.google.com/this_does_not_exist')
RestClient::NotFound: 404 Not Found
from /Users/piperwarrior/.rvm/gems/ruby-2.2.1/gems/rest-client-2.0.0/lib/restclient/abstract_response.rb:223:in `exception_with_response'
from /Users/piperwarrior/.rvm/gems/ruby-2.2.1/gems/rest-client-2.0.0/lib/restclient/abstract_response.rb:103:in `return!'
from /Users/piperwarrior/.rvm/gems/ruby-2.2.1/gems/rest-client-2.0.0/lib/restclient/request.rb:860:in `process_result'
from /Users/piperwarrior/.rvm/gems/ruby-2.2.1/gems/rest-client-2.0.0/lib/restclient/request.rb:776:in `block in transmit'
from /Users/piperwarrior/.rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/net/http.rb:853:in `start'
from /Users/piperwarrior/.rvm/gems/ruby-2.2.1/gems/rest-client-2.0.0/lib/restclient/request.rb:766:in `transmit'
from /Users/piperwarrior/.rvm/gems/ruby-2.2.1/gems/rest-client-2.0.0/lib/restclient/request.rb:215:in `execute'
from /Users/piperwarrior/.rvm/gems/ruby-2.2.1/gems/rest-client-2.0.0/lib/restclient/request.rb:52:in `execute'
from /Users/piperwarrior/.rvm/gems/ruby-2.2.1/gems/rest-client-2.0.0/lib/restclient.rb:67:in `get'
from (irb):54
from /Users/piperwarrior/.rvm/rubies/ruby-2.2.1/bin/irb:11:in `<main>'
2.2.1 :055 >
答案 0 :(得分:1)
- 表示
200
和207
之间的结果代码,将返回RestClient::Response
- 对于结果代码
,则会进行重定向301
,302
或307
,如果请求为GET
或HEAD
- 对于结果代码
303
,将遵循重定向并将请求转换为GET
- 对于其他情况,将提出持有响应的
RestClient::Exception
;将针对已知错误代码抛出特定的异常类- 在异常上调用
.response
以获取服务器的响应
所以是的,这是预期的行为,可以使用e.response
检索响应对象。