views:

31

answers:

1

Given the code below ...

Net::HTTP.start('localhost', 4000) do |http|
    #
    #   usual stuff omitted for clarity
    #
    @response = http.request(req)
end

... if a (well behaved) server returns a 401 (Unauthorized) response, how do I get at the WWW_Authenticate header?

The best solution I've got isn't at all good ...

class Net::HTTPUnauthorized
    def get_header(h)
        _return = nil

        target = h.upcase

        self.header.each_header do |k, v|
            if k.upcase == target
                _return = v
                break
            end
        end

        _return
    end
end

Chris

+1  A: 

One option would be to use halorgium's Rack-Client, which wraps Net::HTTP with a Rack endpoint. You would then interact with the remote server as though it were a Rack application:

response = Rack::Client.get("http://localhost:4000/foo/bar.baz")
response.code
# => 401
response.headers['WWW-Authenticate']
# => 'Basic realm="Control Panel"'
James A. Rosen