Dave Dave - 4 months ago 26
HTTP Question

In RoR, how do I get the status code when requesting a web page through a proxy?

I’m using Rails 4.2.7. How do I get the status code when making a request? I’m trying the below

uri = URI(url)
content = nil
status = nil
content_type = nil
res1 = Net::HTTP.SOCKSProxy('', 50001).start(uri.host, uri.port) do |http|
puts "launching #{uri.path}"
resp = http.get(uri.path)
status = resp.status
content = resp.content
content_type = resp['content-type']

but its resulting in the below error. I can clearly see its a 403, but I would like to have that nice and neat within a variable, or at least have some kind of error I can catch

Error during processing: undefined method `status' for #<Net::HTTPForbidden 403 Forbidden readbody=true>
/Users/davea/Documents/workspace/myproject/app/helpers/webpage_helper.rb:77:in `block in get_content'
/Users/davea/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/net/http.rb:853:in `start'
/Users/davea/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/net/http.rb:584:in `start'
/Users/davea/Documents/workspace/myproject/app/helpers/webpage_helper.rb:74:in `get_content'


I think you want resp.code.

One way to find out is to use the pry gem. Once installed you can put binding.pry just after your http.get line and run your code. When it hits the pry line it will stop executing and open up a IRB prompt and then you can play around with resp directly trying different things. One really nifty feature is you can cd resp and are now "in" the object itself. Type ls and you can see all the methods available. Makes figuring this sort of thing out much easier.