httparty 0.24.3 → 0.25.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. checksums.yaml +4 -4
  2. data/CONTRIBUTING.md +2 -4
  3. data/Rakefile +3 -1
  4. data/bin/httparty +32 -11
  5. data/docs/README.md +39 -5
  6. data/examples/README.md +12 -23
  7. data/examples/basic.rb +2 -2
  8. data/examples/basic_auth.rb +19 -0
  9. data/examples/cookies.rb +20 -0
  10. data/examples/crack.rb +2 -2
  11. data/examples/custom_parsers.rb +2 -2
  12. data/examples/debug_output.rb +17 -0
  13. data/examples/google.rb +2 -2
  14. data/examples/headers_and_user_agents.rb +2 -2
  15. data/examples/idn.rb +4 -3
  16. data/examples/logging.rb +2 -2
  17. data/examples/nokogiri_html_parser.rb +2 -2
  18. data/examples/party_foul_mode.rb +1 -0
  19. data/examples/peer_cert.rb +2 -2
  20. data/examples/rescue_json.rb +5 -3
  21. data/examples/stackexchange.rb +2 -2
  22. data/examples/stream_download.rb +2 -2
  23. data/examples/whoismyrep.rb +2 -2
  24. data/httparty.gemspec +5 -2
  25. data/lib/httparty/connection_adapter.rb +6 -6
  26. data/lib/httparty/cookie_hash.rb +1 -1
  27. data/lib/httparty/headers_processor.rb +5 -2
  28. data/lib/httparty/logger/apache_formatter.rb +14 -1
  29. data/lib/httparty/logger/curl_formatter.rb +31 -7
  30. data/lib/httparty/logger/logger.rb +2 -1
  31. data/lib/httparty/module_inheritable_attributes.rb +13 -13
  32. data/lib/httparty/net_digest_auth.rb +9 -11
  33. data/lib/httparty/parser.rb +2 -1
  34. data/lib/httparty/request/body.rb +5 -3
  35. data/lib/httparty/request/streaming_multipart_body.rb +9 -2
  36. data/lib/httparty/request.rb +85 -25
  37. data/lib/httparty/response.rb +16 -4
  38. data/lib/httparty/text_encoder.rb +6 -6
  39. data/lib/httparty/utils.rb +1 -5
  40. data/lib/httparty/version.rb +1 -1
  41. data/lib/httparty.rb +35 -23
  42. metadata +8 -18
  43. data/.github/dependabot.yml +0 -6
  44. data/.github/workflows/ci.yml +0 -24
  45. data/.rubocop.yml +0 -92
  46. data/.rubocop_todo.yml +0 -124
  47. data/Gemfile +0 -27
  48. data/Guardfile +0 -17
  49. data/cucumber.yml +0 -1
  50. data/examples/aaws.rb +0 -36
  51. data/examples/delicious.rb +0 -37
  52. data/examples/rubyurl.rb +0 -14
  53. data/examples/tripit_sign_in.rb +0 -44
  54. data/examples/twitter.rb +0 -31
  55. data/script/release +0 -42
  56. data/website/css/common.css +0 -47
  57. data/website/index.html +0 -73
@@ -41,7 +41,7 @@ module HTTParty
41
41
  def log_response
42
42
  log IN, "HTTP/#{response.http_version} #{response.code}"
43
43
  log_response_headers
44
- log IN, "\n#{response.body}"
44
+ log IN, "\n", response.body
45
45
  log IN
46
46
  end
47
47
 
@@ -53,7 +53,7 @@ module HTTParty
53
53
  request.path.to_s
54
54
  end
55
55
 
56
- log OUT, "#{http_method} #{uri}"
56
+ log OUT, http_method, ' ', uri
57
57
  end
58
58
 
59
59
  def log_headers
@@ -64,27 +64,51 @@ module HTTParty
64
64
  end
65
65
 
66
66
  def log_query
67
- return unless request.options[:query]
67
+ query = request.options[:query]
68
+ return unless query
68
69
 
69
70
  log OUT, 'Query: '
70
- log_hash request.options[:query]
71
+ query.respond_to?(:to_hash) ? log_hash(query.to_hash) : log(OUT, query)
71
72
  end
72
73
 
73
74
  def log_response_headers
74
75
  headers = response.respond_to?(:headers) ? response.headers : response
75
76
  response.each_header do |response_header|
76
- log IN, "#{response_header.capitalize}: #{headers[response_header]}"
77
+ log IN, response_header.capitalize, ': ', headers[response_header]
77
78
  end
78
79
  end
79
80
 
80
81
  def log_hash(hash)
81
- hash.each { |k, v| log(OUT, "#{k}: #{v}") }
82
+ hash.each { |k, v| log(OUT, k, ': ', v) }
82
83
  end
83
84
 
84
- def log(direction, line = '')
85
+ # Each part is converted before it is joined, so values in mixed
86
+ # encodings can't raise and fail the request just to write a log line.
87
+ def log(direction, *parts)
88
+ line = parts.map { |part| encode_log(part) }.join
85
89
  messages << "[#{TAG_NAME}] [#{current_time}] #{direction} #{line}"
86
90
  end
87
91
 
92
+ # Binary and broken UTF-8 are relabeled and scrubbed so readable text
93
+ # survives; other charsets are converted.
94
+ def encode_log(part)
95
+ text = part.to_s
96
+ return text if text.encoding == Encoding::UTF_8 && text.valid_encoding?
97
+
98
+ if text.encoding == Encoding::BINARY || text.encoding == Encoding::UTF_8
99
+ relabel_utf8(text)
100
+ else
101
+ text.encode(Encoding::UTF_8, invalid: :replace, undef: :replace)
102
+ end
103
+ rescue Encoding::ConverterNotFoundError
104
+ relabel_utf8(text)
105
+ end
106
+
107
+ def relabel_utf8(text)
108
+ utf8 = text.dup.force_encoding(Encoding::UTF_8)
109
+ utf8.valid_encoding? ? utf8 : utf8.scrub
110
+ end
111
+
88
112
  def current_time
89
113
  Time.now.strftime("%Y-%m-%d %H:%M:%S %z")
90
114
  end
@@ -15,8 +15,9 @@ module HTTParty
15
15
  end
16
16
 
17
17
  def self.add_formatter(name, formatter)
18
+ name = name.to_sym
18
19
  raise HTTParty::Error.new("Log Formatter with name #{name} already exists") if formatters.include?(name)
19
- formatters.merge!(name.to_sym => formatter)
20
+ formatters.merge!(name => formatter)
20
21
  end
21
22
 
22
23
  def self.build(logger, level, formatter)
@@ -7,20 +7,20 @@ module HTTParty
7
7
  end
8
8
 
9
9
  # borrowed from Rails 3.2 ActiveSupport
10
- def self.hash_deep_dup(hash)
11
- duplicate = hash.dup
12
-
13
- duplicate.each_pair do |key, value|
14
- if value.is_a?(Hash)
10
+ def self.hash_deep_dup(object)
11
+ case object
12
+ when Hash
13
+ object.each_with_object(object.dup) do |(key, value), duplicate|
15
14
  duplicate[key] = hash_deep_dup(value)
16
- elsif value.is_a?(Proc)
17
- duplicate[key] = value.dup
18
- else
19
- duplicate[key] = value
20
15
  end
16
+ when Array
17
+ copy = object.dup.map! { |value| hash_deep_dup(value) }
18
+ object.frozen? ? copy.freeze : copy
19
+ when Proc
20
+ object.dup
21
+ else
22
+ object
21
23
  end
22
-
23
- duplicate
24
24
  end
25
25
 
26
26
  module ClassMethods #:nodoc:
@@ -44,8 +44,8 @@ module HTTParty
44
44
  if instance_variable_get(ivar).respond_to?(:merge)
45
45
  subclass.class_eval <<~RUBY, __FILE__, __LINE__ + 1
46
46
  def self.#{inheritable_attribute}
47
- duplicate = ModuleInheritableAttributes.hash_deep_dup(#{ivar})
48
- #{ivar} = superclass.#{inheritable_attribute}.merge(duplicate)
47
+ duplicate = superclass.#{inheritable_attribute}.merge(#{ivar})
48
+ #{ivar} = ModuleInheritableAttributes.hash_deep_dup(duplicate)
49
49
  end
50
50
  RUBY
51
51
  end
@@ -18,8 +18,9 @@ module Net
18
18
  add_field('Authorization', v)
19
19
  end
20
20
 
21
+ # Net::HTTP joins repeated fields with ", ", but cookies are split by "; ".
21
22
  authenticator.cookie_header.each do |v|
22
- add_field('Cookie', v)
23
+ self['Cookie'] = [self['Cookie'], v].compact.join('; ')
23
24
  end
24
25
  end
25
26
 
@@ -72,20 +73,17 @@ module Net
72
73
  non_quoted = $1.gsub(/(\w+)="(.*?)"/) { params[$1] = $2 }
73
74
  non_quoted.gsub(/(\w+)=([^,]*)/) { params[$1] = $2 }
74
75
  end
76
+ # The server can offer a list, but the client has to answer with one.
77
+ params['qop'] = 'auth' if params['qop'].to_s.split(',').map(&:strip).include?('auth')
75
78
  params
76
79
  end
77
80
 
81
+ # Send back each cookie's name=value only. Attributes like Path and
82
+ # HttpOnly are for the client, and cookies share one header, split by "; ".
78
83
  def parse_cookies(response_header)
79
- return [] unless response_header['Set-Cookie']
80
-
81
- cookies = response_header['Set-Cookie'].split('; ')
82
-
83
- cookies.reduce([]) do |ret, cookie|
84
- ret << cookie
85
- ret
86
- end
87
-
88
- cookies
84
+ set_cookies = response_header.respond_to?(:get_fields) ? response_header.get_fields('Set-Cookie') : response_header['Set-Cookie']
85
+ cookies = Array(set_cookies).map { |cookie| cookie.split(';', 2).first.to_s.strip }.reject(&:empty?)
86
+ cookies.empty? ? [] : [cookies.join('; ')]
89
87
  end
90
88
 
91
89
  def opaque_present?
@@ -80,7 +80,8 @@ module HTTParty
80
80
  # @return [Symbol]
81
81
  # @return [nil] mime type not supported
82
82
  def self.format_from_mimetype(mimetype)
83
- formats[formats.keys.detect {|k| mimetype.include?(k)}]
83
+ mimetype = mimetype.downcase
84
+ formats[formats.keys.detect {|k| mimetype.include?(k.downcase)}]
84
85
  end
85
86
 
86
87
  # @return [Array<Symbol>] list of supported formats
@@ -41,7 +41,7 @@ module HTTParty
41
41
  end
42
42
 
43
43
  def prepared_parts
44
- normalized_params = params.flat_map { |key, value| HashConversions.normalize_keys(key, value) }
44
+ normalized_params = params.to_hash.flat_map { |key, value| HashConversions.normalize_keys(key, value) }
45
45
  normalized_params.map do |key, value|
46
46
  [key, value, file?(value)]
47
47
  end
@@ -57,7 +57,7 @@ module HTTParty
57
57
  }.freeze
58
58
 
59
59
  def generate_multipart
60
- normalized_params = params.flat_map { |key, value| HashConversions.normalize_keys(key, value) }
60
+ normalized_params = params.to_hash.flat_map { |key, value| HashConversions.normalize_keys(key, value) }
61
61
 
62
62
  multipart = normalized_params.inject(''.b) do |memo, (key, value)|
63
63
  memo << "--#{boundary}#{NEWLINE}".b
@@ -91,7 +91,9 @@ module HTTParty
91
91
 
92
92
  def normalize_query(query)
93
93
  if query_string_normalizer
94
- query_string_normalizer.call(query)
94
+ # Normalizers may return an array of pairs, which the query string joins with '&'
95
+ normalized = query_string_normalizer.call(query)
96
+ normalized.respond_to?(:to_ary) ? normalized.to_ary.join('&') : normalized
95
97
  else
96
98
  HashConversions.to_params(query)
97
99
  end
@@ -15,6 +15,7 @@ module HTTParty
15
15
  @header_buffer = nil
16
16
  @header_offset = 0
17
17
  @footer_sent = false
18
+ @read_buffer = ''.b
18
19
  end
19
20
 
20
21
  def size
@@ -27,9 +28,11 @@ module HTTParty
27
28
  return read_all(outbuf) if length.nil?
28
29
 
29
30
  while outbuf.bytesize < length
30
- chunk = read_chunk(length - outbuf.bytesize)
31
+ remaining = length - outbuf.bytesize
32
+ chunk = @read_buffer.empty? ? read_chunk(remaining) : @read_buffer
31
33
  break if chunk.nil?
32
- outbuf << chunk
34
+ outbuf << chunk.byteslice(0, remaining)
35
+ @read_buffer = chunk.byteslice(remaining..-1) || ''.b
33
36
  end
34
37
 
35
38
  outbuf.empty? ? nil : outbuf
@@ -42,6 +45,7 @@ module HTTParty
42
45
  @header_buffer = nil
43
46
  @header_offset = 0
44
47
  @footer_sent = false
48
+ @read_buffer = ''.b
45
49
  @parts.each do |_key, value, _is_file|
46
50
  value.rewind if value.respond_to?(:rewind)
47
51
  end
@@ -50,6 +54,8 @@ module HTTParty
50
54
  private
51
55
 
52
56
  def read_all(outbuf)
57
+ outbuf << @read_buffer
58
+ @read_buffer = ''.b
53
59
  while (chunk = read_chunk(CHUNK_SIZE))
54
60
  outbuf << chunk
55
61
  end
@@ -110,6 +116,7 @@ module HTTParty
110
116
  if chunk
111
117
  return chunk
112
118
  else
119
+ value.rewind if value.respond_to?(:rewind)
113
120
  @current_file = nil
114
121
  @state = :newline
115
122
  return nil
@@ -20,6 +20,9 @@ module HTTParty
20
20
  ]
21
21
 
22
22
  SupportedURISchemes = ['http', 'https', 'webcal', nil]
23
+ DEFAULT_PORTS = { 'http' => 80, 'https' => 443 }.freeze
24
+ # Headers that describe a request body, and so are dropped along with it
25
+ CONTENT_HEADERS = %w[content-encoding content-language content-length content-location content-type transfer-encoding].freeze
23
26
 
24
27
  NON_RAILS_QUERY_STRING_NORMALIZER = proc do |query|
25
28
  Array(query).sort_by { |a| a[0].to_s }.map do |key, value|
@@ -60,6 +63,7 @@ module HTTParty
60
63
 
61
64
  def initialize(http_method, path, o = {})
62
65
  @changed_hosts = false
66
+ @cross_origin_redirect = false
63
67
  @credentials_sent = false
64
68
 
65
69
  self.http_method = http_method
@@ -81,8 +85,15 @@ module HTTParty
81
85
 
82
86
  @path = if uri.is_a?(uri_adapter)
83
87
  uri
84
- elsif String.try_convert(uri)
85
- uri_adapter.parse(uri).normalize
88
+ elsif (uri_str = String.try_convert(uri))
89
+ # Normalizing an empty path ("", "?query" or "#fragment") with the
90
+ # default URI adapter turns it into "/", which appends an unwanted
91
+ # trailing slash to the base_uri path (breaking e.g. SOAP endpoints).
92
+ # Such a reference means the base_uri itself (RFC 3986 section 5.2.2),
93
+ # so leave it alone and let the uri adapter normalize everything else.
94
+ # See https://github.com/jnunemaker/httparty/issues/742
95
+ parsed_uri = uri_adapter.parse(uri_str)
96
+ empty_path_reference?(parsed_uri) ? parsed_uri : parsed_uri.normalize
86
97
  else
87
98
  raise ArgumentError,
88
99
  "bad argument (expected #{uri_adapter} object or URI string)"
@@ -93,16 +104,17 @@ module HTTParty
93
104
  if uri.respond_to? :request_uri
94
105
  uri.request_uri
95
106
  else
96
- uri.path
107
+ uri.query ? "#{uri.path}?#{uri.query}" : uri.path
97
108
  end
98
109
  end
99
110
 
100
111
  def uri
101
- if redirect && path.relative? && path.path[0] != '/'
102
- last_uri_host = @last_uri.path.gsub(/[^\/]+$/, '')
103
-
104
- path.path = "/#{path.path}" if last_uri_host[-1] != '/'
105
- path.path = "#{last_uri_host}#{path.path}"
112
+ # Resolve a relative redirect Location ("baz", "../baz", "?page=2", "")
113
+ # against the URL that redirected (RFC 3986 section 5.2). Keep it as an
114
+ # absolute path so later calls resolve it to the same URL. A Location
115
+ # with a host is used as given below.
116
+ if redirect && path.relative? && path.host.nil?
117
+ @path = options[:uri_adapter].parse(request_uri((@last_uri + path).normalize))
106
118
  end
107
119
 
108
120
  if path.relative? && path.host
@@ -171,7 +183,7 @@ module HTTParty
171
183
  end
172
184
 
173
185
  handle_host_redirection if response_redirects?
174
- result = handle_unauthorized
186
+ result = handle_unauthorized(&block)
175
187
  result ||= handle_response(chunked_body, &block)
176
188
  result
177
189
  rescue *COMMON_NETWORK_ERRORS => e
@@ -180,7 +192,7 @@ module HTTParty
180
192
  end
181
193
 
182
194
  def handle_unauthorized(&block)
183
- return unless digest_auth? && response_unauthorized? && response_has_digest_auth_challenge?
195
+ return unless digest_auth? && send_authorization_header? && response_unauthorized? && response_has_digest_auth_challenge?
184
196
  return if @credentials_sent
185
197
  @credentials_sent = true
186
198
  perform(&block)
@@ -191,9 +203,7 @@ module HTTParty
191
203
  end
192
204
 
193
205
  def _dump(_level)
194
- opts = options.dup
195
- opts.delete(:logger)
196
- opts.delete(:parser) if opts[:parser] && opts[:parser].is_a?(Proc)
206
+ opts = options.reject { |key, value| value.is_a?(Proc) || %i[logger debug_output].include?(key) }
197
207
  Marshal.dump([http_method, path, opts, last_response, @last_uri, @raw_request])
198
208
  end
199
209
 
@@ -230,6 +240,10 @@ module HTTParty
230
240
  def setup_raw_request
231
241
  if options[:headers].respond_to?(:to_hash)
232
242
  headers_hash = options[:headers].to_hash
243
+ unless send_authorization_header?
244
+ # Header names are case-insensitive, and reject leaves the caller's hash alone
245
+ headers_hash = headers_hash.reject { |name, _| name.to_s.casecmp?('authorization') }
246
+ end
233
247
  else
234
248
  headers_hash = nil
235
249
  end
@@ -266,7 +280,7 @@ module HTTParty
266
280
  @raw_request.basic_auth(username, password)
267
281
  @credentials_sent = true
268
282
  end
269
- setup_digest_auth if digest_auth? && response_unauthorized? && response_has_digest_auth_challenge?
283
+ setup_digest_auth if digest_auth? && send_authorization_header? && response_unauthorized? && response_has_digest_auth_challenge?
270
284
  end
271
285
 
272
286
  def digest_auth?
@@ -335,10 +349,14 @@ module HTTParty
335
349
  logger = HTTParty::Logger.build(options[:logger], options[:log_level], options[:log_format])
336
350
  logger.format(self, last_response)
337
351
  end
338
- self.path = last_response['location']
352
+ # A relative Location is resolved against the current URL in #uri, so
353
+ # it isn't normalized first: Addressable would drop the "../" in it.
354
+ location = options[:uri_adapter].parse(last_response['location'])
355
+ self.path = location.relative? && location.host.nil? ? location : location.normalize
339
356
  self.redirect = true
340
357
  if last_response.class == Net::HTTPSeeOther
341
- unless options[:maintain_method_across_redirects] && options[:resend_on_redirect]
358
+ # A 303 turns the request into a GET, but a HEAD stays a HEAD (RFC 9110)
359
+ unless options[:maintain_method_across_redirects] && (options[:resend_on_redirect] || http_method == Net::HTTP::Head)
342
360
  self.http_method = Net::HTTP::Get
343
361
  end
344
362
  elsif last_response.code != '307' && last_response.code != '308'
@@ -349,15 +367,36 @@ module HTTParty
349
367
  if http_method == Net::HTTP::Get
350
368
  clear_body
351
369
  end
352
- capture_cookies(last_response)
370
+ # Cookies stay with the origin they came from. HTTParty doesn't track the
371
+ # Set-Cookie Domain attribute, so a redirect to another origin gets none
372
+ # of them; that origin's own Set-Cookie cookies are collected from here on.
373
+ @cross_origin_redirect ? drop_cookies : capture_cookies(last_response)
353
374
  perform(&block)
354
375
  end
355
376
 
356
377
  def handle_host_redirection
357
378
  check_duplicate_location_header
358
379
  redirect_path = options[:uri_adapter].parse(last_response['location']).normalize
359
- return if redirect_path.relative? || path.host == redirect_path.host || uri.host == redirect_path.host
360
- @changed_hosts = true
380
+ # A Location without a host ("/x", "../x", "?a") stays on the same origin.
381
+ # A scheme-relative one ("//other.example.com/x") has a host to compare.
382
+ @cross_origin_redirect = !(redirect_path.relative? && redirect_path.host.nil?) &&
383
+ cross_origin_redirect?(@last_uri, redirect_path)
384
+ @changed_hosts = true if @cross_origin_redirect
385
+ end
386
+
387
+ # Credentials only follow a redirect to the same scheme, host and port, as
388
+ # in curl and Python requests. An http -> https upgrade on the default
389
+ # ports keeps them, and once dropped they stay dropped for the request.
390
+ def cross_origin_redirect?(from, to)
391
+ return true unless from.host.to_s.casecmp?(to.host.to_s)
392
+
393
+ to_scheme = (to.scheme || from.scheme).to_s.downcase
394
+ from_scheme = from.scheme.to_s.downcase
395
+ from_port = from.port || DEFAULT_PORTS[from_scheme]
396
+ to_port = to.port || DEFAULT_PORTS[to_scheme]
397
+ return false if from_scheme == to_scheme && from_port == to_port
398
+
399
+ !(from_scheme == 'http' && from_port == 80 && to_scheme == 'https' && to_port == 443)
361
400
  end
362
401
 
363
402
  def check_duplicate_location_header
@@ -385,21 +424,36 @@ module HTTParty
385
424
  end
386
425
 
387
426
  # Some Web Application Firewalls reject incoming GET requests that have a body
388
- # if we redirect, and the resulting verb is GET then we will clear the body that
389
- # may be left behind from the initiating request
427
+ # if we redirect, and the resulting verb is GET then we will clear the body (or
428
+ # body_stream) that may be left behind from the initiating request, along with
429
+ # the header fields that described it (RFC 9110, section 15.4)
390
430
  def clear_body
391
431
  options[:body] = nil
432
+ options[:body_stream] = nil
392
433
  @raw_request.body = nil
434
+ return unless options[:headers].respond_to?(:to_hash)
435
+
436
+ options[:headers] = options[:headers].to_hash.reject do |name, _|
437
+ CONTENT_HEADERS.include?(name.to_s.downcase)
438
+ end
393
439
  end
394
440
 
395
441
  def capture_cookies(response)
396
442
  return unless response['Set-Cookie']
443
+ headers = options[:headers].respond_to?(:to_hash) ? options[:headers].to_hash : {}
444
+ # Class and request cookies are stored as "cookie", so match any case
445
+ cookie_names = headers.keys.select { |name| name.to_s.casecmp?('cookie') }
397
446
  cookies_hash = HTTParty::CookieHash.new
398
- cookies_hash.add_cookies(options[:headers].to_hash['Cookie']) if options[:headers] && options[:headers].to_hash['Cookie']
447
+ cookie_names.each { |name| cookies_hash.add_cookies(headers[name]) }
399
448
  response.get_fields('Set-Cookie').each { |cookie| cookies_hash.add_cookies(cookie) }
400
449
 
401
- options[:headers] ||= {}
402
- options[:headers]['Cookie'] = cookies_hash.to_cookie_string
450
+ options[:headers] = headers.reject { |name, _| cookie_names.include?(name) }
451
+ .merge('Cookie' => cookies_hash.to_cookie_string)
452
+ end
453
+
454
+ def drop_cookies
455
+ return unless options[:headers].respond_to?(:to_hash)
456
+ options[:headers] = options[:headers].to_hash.reject { |name, _| name.to_s.casecmp?('cookie') }
403
457
  end
404
458
 
405
459
  # Uses the HTTP Content-Type header to determine the format of the
@@ -413,7 +467,7 @@ module HTTParty
413
467
 
414
468
  def validate
415
469
  raise HTTParty::RedirectionTooDeep.new(last_response), 'HTTP redirects too deep' if options[:limit].to_i <= 0
416
- raise ArgumentError, 'only get, post, patch, put, delete, head, and options methods are supported' unless SupportedHTTPMethods.include?(http_method)
470
+ raise ArgumentError, "only #{SupportedHTTPMethods.map { |m| m::METHOD.downcase }.join(', ')} methods are supported" unless SupportedHTTPMethods.include?(http_method)
417
471
  raise ArgumentError, ':headers must be a hash' if options[:headers] && !options[:headers].respond_to?(:to_hash)
418
472
  raise ArgumentError, 'only one authentication method, :basic_auth or :digest_auth may be used at a time' if options[:basic_auth] && options[:digest_auth]
419
473
  raise ArgumentError, ':basic_auth must be a hash' if options[:basic_auth] && !options[:basic_auth].respond_to?(:to_hash)
@@ -445,6 +499,12 @@ module HTTParty
445
499
  ).call
446
500
  end
447
501
 
502
+ # A reference with no scheme, host or path ("", "?query" or "#fragment")
503
+ # refers to the base URI itself (RFC 3986 section 5.2.2).
504
+ def empty_path_reference?(uri)
505
+ uri.scheme.nil? && uri.host.nil? && uri.path.to_s.empty?
506
+ end
507
+
448
508
  def validate_uri_safety!(new_uri)
449
509
  return if options[:skip_uri_validation]
450
510
 
@@ -34,7 +34,8 @@ module HTTParty
34
34
  end
35
35
 
36
36
  def parsed_response
37
- @parsed_response ||= @parsed_block.call
37
+ return @parsed_response if defined?(@parsed_response)
38
+ @parsed_response = @parsed_block.call
38
39
  end
39
40
 
40
41
  def code
@@ -52,7 +53,7 @@ module HTTParty
52
53
 
53
54
  def inspect
54
55
  inspect_id = ::Kernel::format '%x', (object_id * 2)
55
- %(#<#{self.class}:0x#{inspect_id} parsed_response=#{parsed_response.inspect}, @response=#{response.inspect}, @headers=#{headers.inspect}>)
56
+ %(#<#{self.class}:0x#{inspect_id} #{inspect_parsed_response}, @response=#{response.inspect}, @headers=#{headers.inspect}>)
56
57
  end
57
58
 
58
59
  CODES_TO_OBJ = ::Net::HTTPResponse::CODE_CLASS_TO_OBJ.merge ::Net::HTTPResponse::CODE_TO_OBJ
@@ -94,8 +95,12 @@ module HTTParty
94
95
  end
95
96
 
96
97
  def pretty_print(pp)
97
- if !parsed_response.nil? && parsed_response.respond_to?(:pretty_print)
98
- parsed_response.pretty_print(pp)
98
+ parsed = parsed_response
99
+ rescue StandardError
100
+ super
101
+ else
102
+ if !parsed.nil? && parsed.respond_to?(:pretty_print)
103
+ parsed.pretty_print(pp)
99
104
  else
100
105
  super
101
106
  end
@@ -145,6 +150,13 @@ module HTTParty
145
150
 
146
151
  private
147
152
 
153
+ # Debugging output must not raise, so show a parse error and the raw body.
154
+ def inspect_parsed_response
155
+ "parsed_response=#{parsed_response.inspect}"
156
+ rescue StandardError => e
157
+ "parsed_response=#<#{e.class}: #{e.message.inspect}>, body=#{body.inspect}"
158
+ end
159
+
148
160
  def code_matches?(matcher)
149
161
  case matcher
150
162
  when Range
@@ -11,7 +11,7 @@ module HTTParty
11
11
  end
12
12
 
13
13
  def call
14
- if can_encode?
14
+ if charset
15
15
  encoded_text
16
16
  else
17
17
  text
@@ -20,10 +20,6 @@ module HTTParty
20
20
 
21
21
  private
22
22
 
23
- def can_encode?
24
- ''.respond_to?(:encoding) && charset
25
- end
26
-
27
23
  def encoded_text
28
24
  if 'utf-16'.casecmp(charset) == 0
29
25
  encode_utf_16
@@ -52,7 +48,11 @@ module HTTParty
52
48
  # NOTE: This will raise an argument error if the
53
49
  # charset does not exist
54
50
  encoding = Encoding.find(charset)
55
- text.force_encoding(encoding.to_s)
51
+ # Dummy encodings (UTF-7, UTF-32, ISO-2022-JP) raise on strip, regexes
52
+ # and parsing, so the body keeps the bytes it arrived with.
53
+ return text if encoding.dummy?
54
+
55
+ text.force_encoding(encoding)
56
56
  rescue ArgumentError
57
57
  text
58
58
  end
@@ -3,11 +3,7 @@
3
3
  module HTTParty
4
4
  module Utils
5
5
  def self.stringify_keys(hash)
6
- return hash.transform_keys(&:to_s) if hash.respond_to?(:transform_keys)
7
-
8
- hash.each_with_object({}) do |(key, value), new_hash|
9
- new_hash[key.to_s] = value
10
- end
6
+ hash.transform_keys(&:to_s)
11
7
  end
12
8
  end
13
9
  end
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module HTTParty
4
- VERSION = '0.24.3'
4
+ VERSION = '0.25.1'
5
5
  end