Tag: open-uri

Ruby – Sprawdzanie dostępności linku ze znakami z UTF-8

Przed kilkoma dniami natrafiłem na pewien problem. Mianowicie open-uri i metoda open nie działają dla znaków z utf-8 (czyli między innymi dla stron gdzie fragment URLa ma "ogonki"). W związku z czym, taki fragment kodu będzie zawsze zwracał fałsz, mimo tego, że pod adresem istnieje strona:

# coding: utf-8
# Wesja rzecz jasna uproszczona - bez obsługi timeoutów itd
url = 'http://www.nina.gov.pl/nina/czołówka'
io_thing = open(url)
correct = io_thing.status[0] == '200'

Zasadniczo bez obsługi błędów będziemy dostawać taki oto wyjątek:

 bad URI(is not URI?): www.nina.gov.pl/nina/czołówka (URI::InvalidURIError)

Rozwiązanie tego problemu może nie jest zbyt eleganckie ale działa:

# coding: utf-8
require 'open-uri'
require 'net/http'

url = 'http://www.nina.gov.pl/nina/czołówka'
url = URI.parse(URI.encode(url))

correct = false
level = 0
while(!correct && level < 10) do
  requst = Net::HTTP.new(url.host, url.port)
  if url.to_s.include?('https')
    requst.use_ssl = true
    requst.verify_mode = OpenSSL::SSL::VERIFY_NONE
  end
  
  requst.start do |http|
    http = http.head(url.request_uri)
    if http.code == "200"
      correct = true
    else
      url = URI.parse(URI.encode(http.header['location'] ))
    end
    level += 1
  end
end

http.head nie podąża za przekierowaniami więc musimy robić to sami.

Ruby 1.8.7, Open-Uri and HTTPS (SSL) websites

Using open-uri Ruby library to open http websites is really easy:

begin
  io_thing = open(self.check_url.to_s)
  io_thing.status[0] == '200'
rescue Exception => e
  false
end

Things get itchy when we want to visit a HTTPS (SSL) self-signed website. Some of them have them corrupted (or expired). Open-uri raises an exception when it occures one of them. To skip certificates testing and get the page we need to turn off certificates verification:

module OpenSSL
  module SSL
    remove_const :VERIFY_PEER
  end
end
OpenSSL::SSL::VERIFY_PEER = OpenSSL::SSL::VERIFY_NONE

However remember to do this carefully, because this can we a security thread to your software.

Copyright © 2024 Closer to Code

Theme by Anders NorenUp ↑