lib/geocoder/lookups/base.rb in geocoder-1.1.9 vs lib/geocoder/lookups/base.rb in geocoder-1.2.0

- old
+ new

@@ -13,10 +13,13 @@ module Geocoder module Lookup class Base + def initialize + @cache = nil + end ## # Human-readable name of the geocoding API. # def name @@ -209,34 +212,59 @@ if cache and body = cache[key] @cache_hit = true else check_api_key_configuration!(query) response = make_api_request(query) + check_response_for_errors!(response) body = response.body + + # apply the charset from the Content-Type header, if possible + ct = response['content-type'] + + if ct && ct['charset'] + charset = ct.split(';').select do |s| + s['charset'] + end.first.to_s.split('=') + if charset.length == 2 + body.force_encoding(charset.last) rescue ArgumentError + end + end + if cache and valid_response?(response) cache[key] = body end @cache_hit = false end body end + def check_response_for_errors!(response) + if response.code.to_i == 400 + raise_error(Geocoder::InvalidRequest) || + warn("Geocoding API error: 400 Bad Request") + elsif response.code.to_i == 401 + raise_error(Geocoder::RequestDenied) || + warn("Geocoding API error: 401 Unauthorized") + elsif response.code.to_i == 402 + raise_error(Geocoder::OverQueryLimitError) || + warn("Geocoding API error: 402 Payment Required") + end + end + ## # Make an HTTP(S) request to a geocoding API and # return the response object. # def make_api_request(query) timeout(configuration.timeout) do uri = URI.parse(query_url(query)) - # client = http_client.new(uri.host, uri.port) - # client.use_ssl = true if configuration.use_https - # client.get(uri.request_uri, configuration.http_headers) + args = [uri.host, uri.port] + args = args.push(uri.user, uri.password) unless uri.user.nil? or uri.password.nil? + opts = {} + opts[:use_ssl] = true if configuration.use_https - http_client.start(uri.host, uri.port) do |client| - client.use_ssl = true if configuration.use_https - req = Net::HTTP::Get.new(uri.request_uri, configuration.http_headers) - req.basic_auth(uri.user, uri.password) if uri.user and uri.password - client.request(req) + http_client.start(*args, opts) do |client| + client.get(uri.request_uri, configuration.http_headers) end end end def check_api_key_configuration!(query)