httparty 0.24.3 → 0.25.0

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 (56) 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 +38 -4
  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 +2 -1
  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/curl_formatter.rb +16 -3
  29. data/lib/httparty/logger/logger.rb +2 -1
  30. data/lib/httparty/module_inheritable_attributes.rb +13 -13
  31. data/lib/httparty/net_digest_auth.rb +9 -11
  32. data/lib/httparty/parser.rb +2 -1
  33. data/lib/httparty/request/body.rb +5 -3
  34. data/lib/httparty/request/streaming_multipart_body.rb +9 -2
  35. data/lib/httparty/request.rb +31 -15
  36. data/lib/httparty/response.rb +16 -4
  37. data/lib/httparty/text_encoder.rb +1 -5
  38. data/lib/httparty/utils.rb +1 -5
  39. data/lib/httparty/version.rb +1 -1
  40. data/lib/httparty.rb +30 -18
  41. metadata +8 -18
  42. data/.github/dependabot.yml +0 -6
  43. data/.github/workflows/ci.yml +0 -24
  44. data/.rubocop.yml +0 -92
  45. data/.rubocop_todo.yml +0 -124
  46. data/Gemfile +0 -27
  47. data/Guardfile +0 -17
  48. data/cucumber.yml +0 -1
  49. data/examples/aaws.rb +0 -36
  50. data/examples/delicious.rb +0 -37
  51. data/examples/rubyurl.rb +0 -14
  52. data/examples/tripit_sign_in.rb +0 -44
  53. data/examples/twitter.rb +0 -31
  54. data/script/release +0 -42
  55. data/website/css/common.css +0 -47
  56. data/website/index.html +0 -73
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 2389baaffd615950f7d364a762d1c7e046e6e1819070b6974137a79737ed5cef
4
- data.tar.gz: 33be08cb6b537efbbe5f691eff3308c9a126f03998d8cda1827ee946edadaffd
3
+ metadata.gz: f086f07dd66b6d801b3a103e90f2c53d42549081324c495e840a118dd6227e49
4
+ data.tar.gz: 460a21e7486089bad58092ac13db538b0b6eabd019ecab8c1f4e5272ba0e700a
5
5
  SHA512:
6
- metadata.gz: 205b2eda67b38f7d4febba842ee9fd13450ffae372f92455ed925b9646ad68872e6a60c7efe7ab97635209737eba19f1efddf8fd6ea58732b8552986304890f9
7
- data.tar.gz: 431bf5342636a7a88bf3d64116535e20d547f089f6cabea8f66700215d9aaafc6ad8903e8205105183d24bb55115d676b28e6026d9c1a0aa969a74d6e53ec471
6
+ metadata.gz: 80f68016d35bab11bb2c218021463a7bd3c6224e6e11fbc2ad703b6f32801f992da79497607a162863b7d0fd25717a88eb25b0248afb673330a72b187b1633f0
7
+ data.tar.gz: a7422e258662e81f4869a21f7c235db0216dbdc41e93ac719bbc512296f46951517be887d8aec84f077dd308bbc46a5262f4341f5dbfe390f64c5f401287768e
data/CONTRIBUTING.md CHANGED
@@ -1,7 +1,7 @@
1
1
  # Contributing
2
2
 
3
3
  * Contributions will not be accepted without tests.
4
- * Please post unconfirmed bugs to the mailing list first: https://groups.google.com/forum/#!forum/httparty-gem
4
+ * Please post unconfirmed bugs to GitHub Discussions first: https://github.com/jnunemaker/httparty/discussions
5
5
  * Don't change the version. The maintainers will handle that when they release.
6
6
  * Always provide as much information and reproducibility as possible when filing an issue or submitting a pull request.
7
7
 
@@ -18,6 +18,4 @@
18
18
 
19
19
  ## Help and Docs
20
20
 
21
- * https://groups.google.com/forum/#!forum/httparty-gem
22
- * http://stackoverflow.com/questions/tagged/httparty
23
- * http://rdoc.info/projects/jnunemaker/httparty
21
+ See [Help and Docs](README.md#help-and-docs) in the README.
data/Rakefile CHANGED
@@ -5,6 +5,8 @@ rescue LoadError
5
5
  end
6
6
 
7
7
  require 'cucumber/rake/task'
8
- Cucumber::Rake::Task.new(:features)
8
+ Cucumber::Rake::Task.new(:features) do |t|
9
+ t.cucumber_opts = %w[--format progress]
10
+ end
9
11
 
10
12
  task default: [:spec, :features]
data/bin/httparty CHANGED
@@ -6,33 +6,47 @@ require "pp"
6
6
  $LOAD_PATH.unshift(File.join(File.dirname(__FILE__), "/../lib"))
7
7
  require "httparty"
8
8
 
9
+ ACTIONS = %i[get post patch put delete head options move copy].freeze
10
+
11
+ def usage_error(message)
12
+ abort "#{message}\nUSAGE: #{$PROGRAM_NAME} [options] [url]"
13
+ end
14
+
9
15
  opts = {
10
16
  action: :get,
11
17
  headers: {},
12
18
  verbose: false
13
19
  }
14
20
 
15
- OptionParser.new do |o|
21
+ parser = OptionParser.new do |o|
16
22
  o.banner = "USAGE: #{$PROGRAM_NAME} [options] [url]"
17
23
 
18
24
  o.on("-f",
19
25
  "--format [FORMAT]",
20
26
  "Output format to use instead of pretty-print ruby: " \
21
27
  "plain, csv, json or xml") do |f|
28
+ usage_error "--format needs a value: plain, csv, json or xml" unless f
22
29
  opts[:output_format] = f.downcase.to_sym
23
30
  end
24
31
 
25
32
  o.on("-a",
26
33
  "--action [ACTION]",
27
- "HTTP action: get (default), post, put, delete, head, or options") do |a|
28
- opts[:action] = a.downcase.to_sym
34
+ "HTTP action: get (default), post, patch, put, delete, head, options, move or copy") do |a|
35
+ usage_error "--action needs a value: #{ACTIONS.join(', ')}" unless a
36
+ action = a.downcase.to_sym
37
+ usage_error "Unknown action #{a.inspect}, should be one of: #{ACTIONS.join(', ')}" unless ACTIONS.include?(action)
38
+ opts[:action] = action
29
39
  end
30
40
 
31
41
  o.on("-d",
32
42
  "--data [BODY]",
33
43
  "Data to put in request body (prefix with '@' for file)") do |d|
34
44
  if d =~ /^@/
35
- opts[:body] = open(d[1..-1]).read
45
+ begin
46
+ opts[:body] = open(d[1..-1]).read
47
+ rescue SystemCallError => e
48
+ abort "Could not read #{d[1..-1]}: #{e.message}"
49
+ end
36
50
  else
37
51
  opts[:body] = d
38
52
  end
@@ -40,7 +54,7 @@ OptionParser.new do |o|
40
54
 
41
55
  o.on("-H", "--header [NAME:VALUE]", "Additional HTTP headers in NAME:VALUE form") do |h|
42
56
  abort "Invalid header specification, should be Name:Value" unless h =~ /.+:.+/
43
- name, value = h.split(':')
57
+ name, value = h.split(':', 2)
44
58
  opts[:headers][name.strip] = value.strip
45
59
  end
46
60
 
@@ -50,7 +64,7 @@ OptionParser.new do |o|
50
64
 
51
65
  o.on("-u", "--user [CREDS]", "Use basic authentication. Value should be user:password") do |u|
52
66
  abort "Invalid credentials format. Must be user:password" unless u =~ /.*:.+/
53
- user, password = u.split(':')
67
+ user, password = u.split(':', 2)
54
68
  opts[:basic_auth] = { username: user, password: password }
55
69
  end
56
70
 
@@ -67,13 +81,16 @@ OptionParser.new do |o|
67
81
  puts "Version: #{HTTParty::VERSION}"
68
82
  exit
69
83
  end
70
- end.parse!
84
+ end
71
85
 
72
- if ARGV.empty?
73
- STDERR.puts "You need to provide a URL"
74
- STDERR.puts "USAGE: #{$PROGRAM_NAME} [options] [url]"
86
+ begin
87
+ parser.parse!
88
+ rescue OptionParser::ParseError => e
89
+ usage_error e.message
75
90
  end
76
91
 
92
+ usage_error "You need to provide a URL" if ARGV.empty?
93
+
77
94
  def dump_headers(response)
78
95
  resp_type = Net::HTTPResponse::CODE_TO_OBJ[response.code.to_s]
79
96
  puts "#{response.code} #{resp_type.to_s.sub(/^Net::HTTP/, '')}"
@@ -91,7 +108,11 @@ if opts[:verbose]
91
108
  puts
92
109
  end
93
110
 
94
- response = HTTParty.send(opts[:action], ARGV.first, opts)
111
+ begin
112
+ response = HTTParty.send(opts[:action], ARGV.first, opts)
113
+ rescue URI::InvalidURIError, HTTParty::UnsupportedURIScheme => e
114
+ usage_error "Invalid URL #{ARGV.first}: #{e.message}"
115
+ end
95
116
  if opts[:output_format].nil?
96
117
  dump_headers(response) if opts[:verbose]
97
118
  pp response
data/docs/README.md CHANGED
@@ -6,9 +6,10 @@ Makes http fun again!
6
6
  - [Parsing JSON](#parsing-json)
7
7
  - [File Uploads (Multipart)](#file-uploads-multipart)
8
8
  - [Working with SSL](#working-with-ssl)
9
+ - [Timeouts and Retries](#timeouts-and-retries)
9
10
 
10
11
  ## Parsing JSON
11
- If the response Content Type is `application/json`, HTTParty will parse the response and return Ruby objects such as a hash or array. The default behavior for parsing JSON will return keys as strings. This can be supressed with the `format` option. To get hash keys as symbols:
12
+ If the response Content Type is `application/json`, HTTParty will parse the response and return Ruby objects such as a hash or array. The default behavior for parsing JSON will return keys as strings. This can be suppressed with the `format` option. To get hash keys as symbols:
12
13
 
13
14
  ```ruby
14
15
  response = HTTParty.get('http://example.com', format: :plain)
@@ -93,7 +94,7 @@ end
93
94
  #### Using `ssl_ca_file` option
94
95
 
95
96
  ```ruby
96
- # Use this example if you are using a pkcs12 file
97
+ # Use this example to verify the server against the CA certificates in a PEM file
97
98
 
98
99
  class Client
99
100
  include HTTParty
@@ -106,7 +107,7 @@ end
106
107
  #### Using `ssl_ca_path` option
107
108
 
108
109
  ```ruby
109
- # Use this example if you are using a pkcs12 file
110
+ # Use this example to verify the server against a directory of CA certificates
110
111
 
111
112
  class Client
112
113
  include HTTParty
@@ -160,7 +161,7 @@ are used to control compression (gzip, etc.) over the wire. Refer to
160
161
  which is specified in the `Accept` and `Content-Type` headers.)
161
162
 
162
163
  Unless you have specific requirements otherwise, we recommend to **not** set
163
- set the `Accept-Encoding` header on HTTParty requests. In this case, `Net::HTTP`
164
+ the `Accept-Encoding` header on HTTParty requests. In this case, `Net::HTTP`
164
165
  will set a sensible default compression scheme and automatically decompress the response.
165
166
 
166
167
  If you explicitly set `Accept-Encoding`, there be dragons:
@@ -221,3 +222,36 @@ res = HTTParty.get('https://example.com/test.json', skip_decompression: true)
221
222
  encoding = res.headers['Content-Encoding']
222
223
  JSON.parse(your_decompression_handling(res.body, encoding))
223
224
  ```
225
+
226
+ ## Timeouts and Retries
227
+
228
+ HTTParty doesn't set timeouts of its own, so a request uses Net::HTTP's defaults: 60 seconds each to open the connection, read and write. Set shorter ones for anything a person is waiting on:
229
+
230
+ ```ruby
231
+ # One request
232
+ HTTParty.get('https://example.com', timeout: 5) # open, read and write
233
+ HTTParty.get('https://example.com', open_timeout: 2, read_timeout: 10)
234
+
235
+ # Every request a class makes
236
+ class Client
237
+ include HTTParty
238
+ base_uri 'https://example.com'
239
+ open_timeout 2
240
+ read_timeout 10
241
+ end
242
+ ```
243
+
244
+ `open_timeout`, `read_timeout` and `write_timeout` take precedence over `timeout`. Timeouts must be an Integer or a Float, and `max_retries` an Integer. The timeout class methods raise `ArgumentError` for anything else, but a request option of another type is silently ignored, so convert values read from `ENV` first (`Integer(ENV['API_TIMEOUT'])`).
245
+
246
+ A timeout raises `Net::OpenTimeout`, `Net::ReadTimeout` or `Net::WriteTimeout` (all `Timeout::Error`s), or `HTTParty::NetworkError` when `foul` is on.
247
+
248
+ Net::HTTP retries a request once, right away, if it times out or the connection fails after it opens, but only for idempotent methods (GET, HEAD, PUT, DELETE, OPTIONS and TRACE). A connection that fails to open isn't retried. So a GET with `read_timeout: 5` can take about 10 seconds before it raises. Use `max_retries` to change the number of retries:
249
+
250
+ ```ruby
251
+ HTTParty.get('https://example.com', read_timeout: 5, max_retries: 0)
252
+
253
+ class Client
254
+ include HTTParty
255
+ default_options[:max_retries] = 0
256
+ end
257
+ ```
data/examples/README.md CHANGED
@@ -1,10 +1,5 @@
1
1
  ## Examples
2
2
 
3
- * [Amazon Book Search](aaws.rb)
4
- * Httparty included into poro class
5
- * Uses `get` requests
6
- * Transforms query params to uppercased params
7
-
8
3
  * [Google Search](google.rb)
9
4
  * Httparty included into poro class
10
5
  * Uses `get` requests
@@ -20,9 +15,9 @@
20
15
  * [More Custom Parsers](custom_parsers.rb)
21
16
  * Create an additional parser for atom or make it the ONLY parser
22
17
 
23
- * [Basic Auth, Delicious](delicious.rb)
24
- * Basic Auth, shows how to merge those into options
25
- * Uses `get` requests
18
+ * [Basic Auth](basic_auth.rb)
19
+ * Sets `basic_auth` for every request from a class
20
+ * Passes `basic_auth` with a single request
26
21
 
27
22
  * [Passing Headers, User Agent](headers_and_user_agents.rb)
28
23
  * Use the class method of Httparty
@@ -33,10 +28,6 @@
33
28
  * Httparty included into poro class
34
29
  * Uses `post` requests
35
30
 
36
- * [Access Rubyurl Shortener](rubyurl.rb)
37
- * Httparty included into poro class
38
- * Uses `post` requests
39
-
40
31
  * [Add a custom log file](logging.rb)
41
32
  * create a log file and have httparty log requests
42
33
 
@@ -45,18 +36,12 @@
45
36
  * Creates methods for different endpoints
46
37
  * Uses `get` requests
47
38
 
48
- * [Accessing Tripit](tripit_sign_in.rb)
49
- * Httparty included into poro class
50
- * Example of using `debug_output` to see headers/urls passed
51
- * Getting and using Cookies
52
- * Uses `get` requests
39
+ * [Cookies](cookies.rb)
40
+ * Sends `cookies` with every request from a class
41
+ * Collects the cookies a server sets with `HTTParty::CookieHash` and sends them back
53
42
 
54
- * [Accessing Twitter](twitter.rb)
55
- * Httparty included into poro class
56
- * Basic Auth
57
- * Loads settings from a config file
58
- * Uses `get` requests
59
- * Uses `post` requests
43
+ * [Debug Output](debug_output.rb)
44
+ * Uses `debug_output` to print each request and response, headers included
60
45
 
61
46
  * [Accessing WhoIsMyRep](whoismyrep.rb)
62
47
  * Httparty included into poro class
@@ -66,6 +51,10 @@
66
51
  * [Rescue Json Error](rescue_json.rb)
67
52
  * Rescue errors due to parsing response
68
53
 
54
+ * [Party foul mode](party_foul_mode.rb)
55
+ * Uses `foul: true` to raise `HTTParty::NetworkError` for connection failures
56
+ * Rescues network errors by their `cause`
57
+
69
58
  * [Download file using stream mode](stream_download.rb)
70
59
  * Uses `get` requests
71
60
  * Uses `stream_body` mode
data/examples/basic.rb CHANGED
@@ -1,5 +1,5 @@
1
- dir = File.expand_path(File.join(File.dirname(__FILE__), '..', 'lib'))
2
- require File.join(dir, 'httparty')
1
+ $LOAD_PATH.unshift(File.expand_path('../lib', __dir__))
2
+ require 'httparty'
3
3
  require 'pp'
4
4
 
5
5
  # You can also use post, put, delete, head, options in the same fashion
@@ -0,0 +1,19 @@
1
+ $LOAD_PATH.unshift(File.expand_path('../lib', __dir__))
2
+ require 'httparty'
3
+ require 'pp'
4
+
5
+ # postman-echo.com accepts the username "postman" with the password "password".
6
+ class PostmanEcho
7
+ include HTTParty
8
+ base_uri 'https://postman-echo.com'
9
+ basic_auth 'postman', 'password' # sent with every request from this class
10
+ end
11
+
12
+ pp PostmanEcho.get('/basic-auth').parsed_response # => {"authenticated"=>true}
13
+
14
+ # Or pass the credentials with a single request.
15
+ response = HTTParty.get(
16
+ 'https://postman-echo.com/basic-auth',
17
+ basic_auth: { username: 'postman', password: 'wrong' }
18
+ )
19
+ puts response.code # => 401
@@ -0,0 +1,20 @@
1
+ $LOAD_PATH.unshift(File.expand_path('../lib', __dir__))
2
+ require 'httparty'
3
+ require 'pp'
4
+
5
+ # postman-echo.com/cookies echoes back the cookies it receives.
6
+ class PostmanEcho
7
+ include HTTParty
8
+ base_uri 'https://postman-echo.com'
9
+ cookies flavor: 'oatmeal' # sent with every request from this class
10
+ end
11
+
12
+ pp PostmanEcho.get('/cookies')['cookies'] # => {"flavor"=>"oatmeal"}
13
+
14
+ # Collect the cookies a server sets and send them back on a later request.
15
+ response = PostmanEcho.get('/cookies/set', query: { size: 'large' }, follow_redirects: false)
16
+ jar = HTTParty::CookieHash.new
17
+ response.headers.get_fields('Set-Cookie').each { |cookie| jar.add_cookies(cookie) }
18
+
19
+ pp PostmanEcho.get('/cookies', cookies: jar)['cookies'].slice('flavor', 'size')
20
+ # => {"flavor"=>"oatmeal", "size"=>"large"}
data/examples/crack.rb CHANGED
@@ -1,8 +1,8 @@
1
1
  require 'rubygems'
2
2
  require 'crack'
3
3
 
4
- dir = File.expand_path(File.join(File.dirname(__FILE__), '..', 'lib'))
5
- require File.join(dir, 'httparty')
4
+ $LOAD_PATH.unshift(File.expand_path('../lib', __dir__))
5
+ require 'httparty'
6
6
  require 'pp'
7
7
 
8
8
  class Rep
@@ -1,5 +1,5 @@
1
- dir = File.expand_path(File.join(File.dirname(__FILE__), '..', 'lib'))
2
- require File.join(dir, 'httparty')
1
+ $LOAD_PATH.unshift(File.expand_path('../lib', __dir__))
2
+ require 'httparty'
3
3
  require 'pp'
4
4
 
5
5
  class ParseAtom
@@ -0,0 +1,17 @@
1
+ $LOAD_PATH.unshift(File.expand_path('../lib', __dir__))
2
+ require 'httparty'
3
+
4
+ # debug_output prints each request and response, headers included, so you can
5
+ # see exactly what goes over the wire. It defaults to $stderr. The output
6
+ # includes credentials such as the Authorization header, so keep it out of
7
+ # production logs.
8
+ class PostmanEcho
9
+ include HTTParty
10
+ base_uri 'https://postman-echo.com'
11
+ debug_output $stdout
12
+ end
13
+
14
+ PostmanEcho.get('/get', query: { party: 'hard' })
15
+
16
+ # Or turn it on for a single request.
17
+ HTTParty.get('https://postman-echo.com/get', debug_output: $stdout)
data/examples/google.rb CHANGED
@@ -1,5 +1,5 @@
1
- dir = File.expand_path(File.join(File.dirname(__FILE__), '..', 'lib'))
2
- require File.join(dir, 'httparty')
1
+ $LOAD_PATH.unshift(File.expand_path('../lib', __dir__))
2
+ require 'httparty'
3
3
  require 'pp'
4
4
 
5
5
  class Google
@@ -1,7 +1,7 @@
1
1
  # To send custom user agents to identify your application to a web service (or mask as a specific browser for testing), send "User-Agent" as a hash to headers as shown below.
2
2
 
3
- dir = File.expand_path(File.join(File.dirname(__FILE__), '..', 'lib'))
4
- require File.join(dir, 'httparty')
3
+ $LOAD_PATH.unshift(File.expand_path('../lib', __dir__))
4
+ require 'httparty'
5
5
  require 'pp'
6
6
 
7
7
  response = HTTParty.get('http://example.com', {
data/examples/idn.rb CHANGED
@@ -1,5 +1,6 @@
1
- dir = File.expand_path(File.join(File.dirname(__FILE__), '..', 'lib'))
2
- require File.join(dir, 'httparty')
1
+ $LOAD_PATH.unshift(File.expand_path('../lib', __dir__))
2
+ require 'httparty'
3
+ require 'addressable/uri'
3
4
  require 'pp'
4
5
 
5
6
  class Idn
@@ -7,4 +8,4 @@ class Idn
7
8
  uri_adapter Addressable::URI
8
9
  end
9
10
 
10
- pp Idn.get("https://i❤️.ws/emojidomain/💎?format=json")
11
+ pp Idn.get("https://i❤.ws/emojidomain/💎?format=json")
data/examples/logging.rb CHANGED
@@ -1,5 +1,5 @@
1
- dir = File.expand_path(File.join(File.dirname(__FILE__), '..', 'lib'))
2
- require File.join(dir, 'httparty')
1
+ $LOAD_PATH.unshift(File.expand_path('../lib', __dir__))
2
+ require 'httparty'
3
3
  require 'logger'
4
4
  require 'pp'
5
5
 
@@ -1,8 +1,8 @@
1
1
  require 'rubygems'
2
2
  require 'nokogiri'
3
3
 
4
- dir = File.expand_path(File.join(File.dirname(__FILE__), '..', 'lib'))
5
- require File.join(dir, 'httparty')
4
+ $LOAD_PATH.unshift(File.expand_path('../lib', __dir__))
5
+ require 'httparty'
6
6
  require 'pp'
7
7
 
8
8
  class HtmlParserIncluded < HTTParty::Parser
@@ -1,3 +1,4 @@
1
+ $LOAD_PATH.unshift(File.expand_path('../lib', __dir__))
1
2
  require 'httparty'
2
3
 
3
4
  class APIClient
@@ -1,5 +1,5 @@
1
- dir = File.expand_path(File.join(File.dirname(__FILE__), '..', 'lib'))
2
- require File.join(dir, 'httparty')
1
+ $LOAD_PATH.unshift(File.expand_path('../lib', __dir__))
2
+ require 'httparty'
3
3
 
4
4
  peer_cert = nil
5
5
  HTTParty.get("https://www.example.com") do |fragment|
@@ -1,10 +1,12 @@
1
- dir = File.expand_path(File.join(File.dirname(__FILE__), '..', 'lib'))
2
- require File.join(dir, 'httparty')
1
+ $LOAD_PATH.unshift(File.expand_path('../lib', __dir__))
2
+ require 'httparty'
3
3
 
4
+ # RubyGems returns plain text here; format: :json forces a JSON parse, which raises.
5
+ #
4
6
  # Take note of the "; 1" at the end of the following line. It's required only if
5
7
  # running this in IRB, because IRB will try to inspect the variable named
6
8
  # "request", triggering the exception.
7
- request = HTTParty.get 'https://rubygems.org/api/v1/versions/doesnotexist.json' ; 1
9
+ request = HTTParty.get 'https://rubygems.org/api/v1/versions/doesnotexist.json', format: :json ; 1
8
10
 
9
11
  # Check an exception due to parsing the response
10
12
  # because HTTParty evaluate the response lazily
@@ -1,5 +1,5 @@
1
- dir = File.expand_path(File.join(File.dirname(__FILE__), '..', 'lib'))
2
- require File.join(dir, 'httparty')
1
+ $LOAD_PATH.unshift(File.expand_path('../lib', __dir__))
2
+ require 'httparty'
3
3
  require 'pp'
4
4
 
5
5
  class StackExchange
@@ -1,5 +1,5 @@
1
- dir = File.expand_path(File.join(File.dirname(__FILE__), '..', 'lib'))
2
- require File.join(dir, 'httparty')
1
+ $LOAD_PATH.unshift(File.expand_path('../lib', __dir__))
2
+ require 'httparty'
3
3
  require 'pp'
4
4
 
5
5
  # download file linux-4.6.4.tar.xz without using the memory
@@ -1,5 +1,5 @@
1
- dir = File.expand_path(File.join(File.dirname(__FILE__), '..', 'lib'))
2
- require File.join(dir, 'httparty')
1
+ $LOAD_PATH.unshift(File.expand_path('../lib', __dir__))
2
+ require 'httparty'
3
3
  require 'pp'
4
4
 
5
5
  class Rep
data/httparty.gemspec CHANGED
@@ -25,8 +25,9 @@ Gem::Specification.new do |s|
25
25
 
26
26
  all_files = `git ls-files`.split("\n")
27
27
  test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
28
+ dev_files = `git ls-files -- .github Gemfile Guardfile '.rubocop*' script`.split("\n")
28
29
 
29
- s.files = all_files - test_files
30
+ s.files = all_files - test_files - dev_files
30
31
  s.executables = `git ls-files -- bin/*`.split("\n").map { |f| File.basename(f) }
31
32
  s.require_paths = ["lib"]
32
33
  end
@@ -17,7 +17,7 @@ module HTTParty
17
17
  # def connection
18
18
  # puts uri
19
19
  # puts options
20
- # Net::HTTP.new(uri)
20
+ # super
21
21
  # end
22
22
  # end
23
23
  #
@@ -25,12 +25,12 @@ module HTTParty
25
25
  # class CountingConnectionAdapter < HTTParty::ConnectionAdapter
26
26
  # @@count = 0
27
27
  #
28
- # self.count
28
+ # def self.count
29
29
  # @@count
30
30
  # end
31
31
  #
32
32
  # def connection
33
- # self.count += 1
33
+ # @@count += 1
34
34
  # super
35
35
  # end
36
36
  # end
@@ -44,7 +44,8 @@ module HTTParty
44
44
  # * :+timeout+: timeout in seconds
45
45
  # * :+open_timeout+: http connection open_timeout in seconds, overrides timeout if set
46
46
  # * :+read_timeout+: http connection read_timeout in seconds, overrides timeout if set
47
- # * :+write_timeout+: http connection write_timeout in seconds, overrides timeout if set (Ruby >= 2.6.0 required)
47
+ # * :+write_timeout+: http connection write_timeout in seconds, overrides timeout if set
48
+ # * :+max_retries+: http connection max_retries (retries of idempotent requests)
48
49
  # * :+debug_output+: see HTTParty::ClassMethods.debug_output.
49
50
  # * :+cert_store+: contains certificate data. see method 'attach_ssl_certificates'
50
51
  # * :+pem+: contains pem client certificate data. see method 'attach_ssl_certificates'
@@ -227,8 +228,7 @@ module HTTParty
227
228
  http.verify_mode = OpenSSL::SSL::VERIFY_PEER
228
229
  end
229
230
 
230
- # This is only Ruby 1.9+
231
- if options[:ssl_version] && http.respond_to?(:ssl_version=)
231
+ if options[:ssl_version]
232
232
  http.ssl_version = options[:ssl_version]
233
233
  end
234
234
  end
@@ -1,7 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  class HTTParty::CookieHash < Hash #:nodoc:
4
- CLIENT_COOKIES = %w(path expires domain path secure httponly samesite)
4
+ CLIENT_COOKIES = %w(path expires max-age domain secure httponly samesite)
5
5
 
6
6
  def add_cookies(data)
7
7
  case data
@@ -11,6 +11,7 @@ module HTTParty
11
11
 
12
12
  def call
13
13
  return unless options[:headers]
14
+ raise ArgumentError, ':headers must be a hash' unless options[:headers].respond_to?(:to_hash)
14
15
 
15
16
  options[:headers] = headers.merge(options[:headers]) if headers.any?
16
17
  options[:headers] = Utils.stringify_keys(process_dynamic_headers)
@@ -18,11 +19,13 @@ module HTTParty
18
19
 
19
20
  private
20
21
 
22
+ # Callable values receive zero arguments or the positional request options hash.
21
23
  def process_dynamic_headers
22
- options[:headers].each_with_object({}) do |header, processed_headers|
24
+ options[:headers].to_hash.each_with_object({}) do |header, processed_headers|
23
25
  key, value = header
24
26
  processed_headers[key] = if value.respond_to?(:call)
25
- value.arity == 0 ? value.call : value.call(options)
27
+ arity = value.respond_to?(:arity) ? value.arity : value.method(:call).arity
28
+ arity == 0 ? value.call : value.call(options)
26
29
  else
27
30
  value
28
31
  end
@@ -64,10 +64,11 @@ 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
@@ -82,7 +83,19 @@ module HTTParty
82
83
  end
83
84
 
84
85
  def log(direction, line = '')
85
- messages << "[#{TAG_NAME}] [#{current_time}] #{direction} #{line}"
86
+ messages << "[#{TAG_NAME}] [#{current_time}] #{direction} #{encode_log(line)}"
87
+ end
88
+
89
+ # Logger lines are joined later, which raises if they mix encodings (a
90
+ # binary body next to a non-ASCII header). Binary is relabeled as UTF-8;
91
+ # other charsets are converted so their text survives.
92
+ def encode_log(line)
93
+ text = line.to_s
94
+ if text.encoding == Encoding::BINARY
95
+ text.dup.force_encoding(Encoding::UTF_8).scrub
96
+ else
97
+ text.encode(Encoding::UTF_8, invalid: :replace, undef: :replace)
98
+ end
86
99
  end
87
100
 
88
101
  def current_time
@@ -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)