在Ruby中检查HTTP代码范围

时间:2016-09-26 18:24:48

标签: php ruby http httpresponse

我希望能够在Ruby中执行以下操作:

我现在只能用PHP代码描述我需要做的事情:

$handle = curl_init($url);
curl_setopt($handle,  CURLOPT_RETURNTRANSFER, TRUE);
$httpResponse = curl_getinfo($handle, CURLINFO_HTTP_CODE);

if ($httpResponse >= 200 && $httpResponse < 300 || $httpResponse == 302) {
     do some action;
}

我知道Net::HTTP我从以下代码获得了以下代码:

require 'net/http'

def check_status(uri_str, limit = 10)
  # You should choose a better exception.
  raise ArgumentError, 'too many HTTP redirects' if limit == 0

  response = Net::HTTP.get_response(URI(uri_str))

  case response
  when Net::HTTPSuccess then #if 200 then do action
    puts "It works!"
    response.code
    #response
  when Net::HTTPRedirection then #if 3xx then check where it goes
    location = response['location']
    check_status(location, limit - 1)
  else
    response.value
  end
end

print check_status('https://git.company.com')

但我不确定如何检查HTTP响应是>= 200还是< 300还是302

我是否必须为所有HTTP responses写一张支票?或者有一种比上面的PHP代码更简单的方法吗?

1 个答案:

答案 0 :(得分:0)

好的,感谢tadman's comment(指出我明显的错误.. xD)和the Tin Man's suggestion,我已将代码更改为以下内容并按预期工作

require 'rest-client'

def check_status(uri_str)

    response = RestClient.get "#{uri_str}"

    case response.code
    when 200...300 || 302
        puts "It works!"
    else
        puts "It doesn't work!"
        puts "#{response.code}"
    end
end

print check_status('https://git.company.com')

注意:您需要安装rest-client gem,方法是:gem install rest-client