net / http请求刚回来200

时间:2013-10-01 09:01:19

标签: ruby-on-rails ruby net-http

我在rails中使用net / http以使用以下代码从URL获取响应代码;

require "net/http"
require "uri"


class Status
def initialize(url)
    @url = url
end

def get_status 
    begin 
        response.code
    rescue Exception => e
        Rails.logger.info("Error #{e}")
    end
end

def active?
    ["200","203","302","301"].include?(get_status) ? true : false
end

private

def lookup
    URI.parse(@url)
end
def http
    Net::HTTP.new(lookup.host, lookup.port)
end
def request
    Net::HTTP::Get.new(lookup.request_uri)
end
def response
    http.request(request)
end
end

虽然它正确地标记了失败,但它显示所有通过或失败的代码作为状态代码:200,我如何获得正确的状态代码?

控制器:

class EnvironmentsController < ApplicationController
  def status
    app = App.find(params[:app_id])
    environment = app.environments.find{|env| env.id.to_s == params[:id]}
    render json: {up:environment.up?}
  end
end

查看:

<%- App.all.each do |app| %>
  <h3><%= app.name %></h3>

  <ul class="app" data-app-id="<%= app.id %>">
    <%- app.environments.each do |environment| %>
      <li class="env" data-env-id="<%= environment.id %>">
      <strong><%= environment.name %></strong>
      <%= environment.url %><span class="status"> Loading. . . </span>
      <!-- <i> Status Code: <% puts response.code %></i> </li> -->
    <% end %>
  </ul>

1 个答案:

答案 0 :(得分:2)

您没有使用Status课程。在您看来response是指当前的回复。

所以而不是:

Status Code: <% puts response.code %>

尝试:

Status Code: <%= Status.new(environment.url).get_status %>