pax_global_header 0000666 0000000 0000000 00000000064 13670224415 0014516 g ustar 00root root 0000000 0000000 52 comment=0e8b82730a143c07c919bb8773f017338f637016
httparty-0.18.1/ 0000775 0000000 0000000 00000000000 13670224415 0013464 5 ustar 00root root 0000000 0000000 httparty-0.18.1/.editorconfig 0000664 0000000 0000000 00000000537 13670224415 0016146 0 ustar 00root root 0000000 0000000 ; This file is for unifying the coding style for different editors and IDEs.
; More information at http://EditorConfig.org
root = true
[*]
end_of_line = lf
trim_trailing_whitespace = true
[**.rb]
indent_size = 2
indent_style = spaces
insert_final_newline = true
[**.xml]
trim_trailing_whitespace = false
[**.html]
trim_trailing_whitespace = false
httparty-0.18.1/.gitignore 0000664 0000000 0000000 00000000136 13670224415 0015454 0 ustar 00root root 0000000 0000000 Gemfile.lock
.DS_Store
.yardoc/
doc/
tmp/
log/
pkg/
*.swp
/.bundle
.rvmrc
coverage
*.gem
.idea httparty-0.18.1/.rubocop.yml 0000664 0000000 0000000 00000004132 13670224415 0015736 0 ustar 00root root 0000000 0000000 inherit_from: .rubocop_todo.yml
# Offense count: 963
# Cop supports --auto-correct.
# Configuration parameters: EnforcedStyle, SupportedStyles.
Style/StringLiterals:
Enabled: false
# Offense count: 327
# Cop supports --auto-correct.
# Configuration parameters: EnforcedStyle, EnforcedStyleForEmptyBraces, SupportedStyles.
Style/SpaceInsideHashLiteralBraces:
Enabled: false
# Offense count: 33
# Cop supports --auto-correct.
# Configuration parameters: EnforcedStyle, SupportedStyles, EnforcedStyleForEmptyBraces, SpaceBeforeBlockParameters.
Style/SpaceInsideBlockBraces:
Enabled: false
# Offense count: 1
# Cop supports --auto-correct.
Style/SpaceBeforeSemicolon:
Enabled: false
# Offense count: 20
# Cop supports --auto-correct.
# Configuration parameters: EnforcedStyle, SupportedStyles.
Style/SignalException:
Enabled: false
# Offense count: 1
# Configuration parameters: Methods.
Style/SingleLineBlockParams:
Enabled: false
# Offense count: 6
# Cop supports --auto-correct.
Style/PerlBackrefs:
Enabled: false
# Offense count: 2
# Cop supports --auto-correct.
# Configuration parameters: AllowAsExpressionSeparator.
Style/Semicolon:
Enabled: false
# Offense count: 77
# Cop supports --auto-correct.
# Configuration parameters: EnforcedStyle, SupportedStyles.
Style/BracesAroundHashParameters:
Enabled: false
# Offense count: 36
Style/Documentation:
Enabled: false
# Offense count: 6
# Cop supports --auto-correct.
# Configuration parameters: EnforcedStyle, SupportedStyles, AllowInnerSlashes.
Style/RegexpLiteral:
Enabled: false
# Offense count: 5
# Cop supports --auto-correct.
Style/NumericLiterals:
MinDigits: 6
# Offense count: 4
# Cop supports --auto-correct.
Lint/UnusedMethodArgument:
Enabled: false
# Offense count: 11
# Cop supports --auto-correct.
Lint/UnusedBlockArgument:
Enabled: false
# Offense count: 1
Lint/Void:
Enabled: false
# Offense count: 22
# Cop supports --auto-correct.
# Configuration parameters: EnforcedStyle, SupportedStyles.
Style/IndentHash:
Enabled: false
# Offense count: 7
# Configuration parameters: MinBodyLength.
Style/GuardClause:
Enabled: false
httparty-0.18.1/.rubocop_todo.yml 0000664 0000000 0000000 00000005365 13670224415 0016774 0 ustar 00root root 0000000 0000000 # This configuration was generated by `rubocop --auto-gen-config`
# on 2015-04-24 07:22:28 +0200 using RuboCop version 0.30.0.
# The point is for the user to remove these configuration records
# one by one as the offenses are removed from the code base.
# Note that changes in the inspected code, or installation of new
# versions of RuboCop, may require this file to be generated again.
# Offense count: 33
Lint/AmbiguousRegexpLiteral:
Enabled: false
# Offense count: 1
# Configuration parameters: AlignWith, SupportedStyles.
Lint/EndAlignment:
Enabled: false
# Offense count: 1
Lint/SuppressedException:
Enabled: false
# Offense count: 5
Lint/UselessAssignment:
Enabled: false
# Offense count: 23
Metrics/AbcSize:
Max: 86
# Offense count: 1
# Configuration parameters: CountComments.
Metrics/ClassLength:
Max: 285
# Offense count: 8
Metrics/CyclomaticComplexity:
Max: 17
# Offense count: 332
# Configuration parameters: AllowURI, URISchemes.
Metrics/LineLength:
Max: 266
# Offense count: 17
# Configuration parameters: CountComments.
Metrics/MethodLength:
Max: 39
# Offense count: 8
Metrics/PerceivedComplexity:
Max: 20
# Offense count: 1
Style/AccessorMethodName:
Enabled: false
# Offense count: 1
Style/AsciiComments:
Enabled: false
# Offense count: 14
# Cop supports --auto-correct.
# Configuration parameters: EnforcedStyle, SupportedStyles, ProceduralMethods, FunctionalMethods, IgnoredMethods.
Style/BlockDelimiters:
Enabled: false
# Offense count: 2
Style/CaseEquality:
Enabled: false
# Offense count: 3
# Configuration parameters: IndentWhenRelativeTo, SupportedStyles, IndentOneStep.
Style/CaseIndentation:
Enabled: false
# Offense count: 4
# Configuration parameters: EnforcedStyle, SupportedStyles.
Style/ClassAndModuleChildren:
Enabled: false
# Offense count: 7
Style/ConstantName:
Enabled: false
# Offense count: 2
Style/EachWithObject:
Enabled: false
# Offense count: 2
# Cop supports --auto-correct.
Style/ElseAlignment:
Enabled: false
# Offense count: 3
# Cop supports --auto-correct.
# Configuration parameters: EnforcedStyle, SupportedStyles.
Style/FirstParameterIndentation:
Enabled: false
# Offense count: 2
# Cop supports --auto-correct.
# Configuration parameters: EnforcedStyle, SupportedStyles, UseHashRocketsWithSymbolValues.
Style/HashSyntax:
Enabled: false
# Offense count: 7
# Cop supports --auto-correct.
# Configuration parameters: MaxLineLength.
Style/IfUnlessModifier:
Enabled: false
# Offense count: 11
# Cop supports --auto-correct.
Style/Lambda:
Enabled: false
# Offense count: 1
# Configuration parameters: EnforcedStyle, MinBodyLength, SupportedStyles.
Style/Next:
Enabled: false
# Offense count: 2
# Configuration parameters: EnforcedStyle, SupportedStyles.
Style/RaiseArgs:
Enabled: false
httparty-0.18.1/.simplecov 0000664 0000000 0000000 00000000041 13670224415 0015461 0 ustar 00root root 0000000 0000000 SimpleCov.start "test_frameworks" httparty-0.18.1/.travis.yml 0000664 0000000 0000000 00000000255 13670224415 0015577 0 ustar 00root root 0000000 0000000 language: ruby
rvm:
- 2.0.0
- 2.1.10
- 2.2.10
- 2.3.8
- 2.4.5
- 2.5.3
- 2.6.1
bundler_args: --without development
before_install: gem install bundler -v '< 2'
httparty-0.18.1/CONTRIBUTING.md 0000664 0000000 0000000 00000002044 13670224415 0015715 0 ustar 00root root 0000000 0000000 # Contributing
* Contributions will not be accepted without tests.
* Please post unconfirmed bugs to the mailing list first: https://groups.google.com/forum/#!forum/httparty-gem
* Don't change the version. The maintainers will handle that when they release.
* Always provide as much information and reproducibility as possible when filing an issue or submitting a pull request.
## Workflow
* Fork the project.
* Run `bundle`
* Run `bundle exec rake`
* Make your feature addition or bug fix.
* Add tests for it. This is important so I don't break it in a future version unintentionally.
* Run `bundle exec rake` (No, REALLY :))
* Commit, do not mess with rakefile, version, or history. (if you want to have your own version, that is fine but bump version in a commit by itself in another branch so I can ignore when I pull)
* Send me a pull request. Bonus points for topic branches.
## Help and Docs
* https://groups.google.com/forum/#!forum/httparty-gem
* http://stackoverflow.com/questions/tagged/httparty
* http://rdoc.info/projects/jnunemaker/httparty
httparty-0.18.1/Changelog.md 0000664 0000000 0000000 00000052655 13670224415 0015712 0 ustar 00root root 0000000 0000000 ## 0.18.1
* [Rename cop Lint/HandleExceptions to Lint/SuppressedException](https://github.com/jnunemaker/httparty/pull/699).
* [Encode keys in query params](https://github.com/jnunemaker/httparty/pull/698).
* [Fixed SSL doc example](https://github.com/jnunemaker/httparty/pull/692).
* [Add a build status badge](https://github.com/jnunemaker/httparty/pull/701).
## 0.18.0
* [Support gzip/deflate transfer encoding when explicit headers are set](https://github.com/jnunemaker/httparty/pull/678).
* [Support edge case cookie format with a blank attribute](https://github.com/jnunemaker/httparty/pull/685).
## 0.17.3
0.17.2 is broken https://github.com/jnunemaker/httparty/issues/681
## 0.17.2
* [Add Response#nil? deprecetion warning](https://github.com/jnunemaker/httparty/pull/680)
## 0.17.1
* [Pass options to dynamic block headers](https://github.com/jnunemaker/httparty/pull/661)
* [Normalize urls with URI adapter to allow International Domain Names support](https://github.com/jnunemaker/httparty/pull/668)
* [Add max_retries support](https://github.com/jnunemaker/httparty/pull/660)
* [Minize gem size by removing test files](https://github.com/jnunemaker/httparty/pull/658)
## 0.17.0
* [Fix encoding of streamed chunk](https://github.com/jnunemaker/httparty/pull/644)
* [Avoid modifying frozen strings](https://github.com/jnunemaker/httparty/pull/649)
* [Expose .connection on fragment block param](https://github.com/jnunemaker/httparty/pull/648)
* [Add support for `Net::HTTP#write_timeout` method (Ruby 2.6.0)](https://github.com/jnunemaker/httparty/pull/647)
## 0.16.4
* [Add support for Ruby 2.6](https://github.com/jnunemaker/httparty/pull/636)
* [Fix a few multipart issues](https://github.com/jnunemaker/httparty/pull/626)
* [Improve a memory usage for https requests](https://github.com/jnunemaker/httparty/pull/625)
* [Add response code to streamed body](https://github.com/jnunemaker/httparty/pull/588)
## 0.16.3
* [Add Logstash-compatible formatter](https://github.com/jnunemaker/httparty/pull/612)
* [Add support for headers specified with symbols](https://github.com/jnunemaker/httparty/pull/622)
* [Fix response object marshalling](https://github.com/jnunemaker/httparty/pull/618)
* [Add ability to send multipart, without passing file](https://github.com/jnunemaker/httparty/pull/615)
* [Fix detection of content_type for multipart payload](https://github.com/jnunemaker/httparty/pull/616)
* [Process dynamic headers before making actual request](https://github.com/jnunemaker/httparty/pull/606)
* [Fix multipart uploads with ActionDispatch::Http::UploadedFile TempFile by using original_filename](https://github.com/jnunemaker/httparty/pull/598)
* [Added support for lock and unlock http requests](https://github.com/jnunemaker/httparty/pull/596)
## 0.16.2
* [Support ActionDispatch::Http::UploadedFile again](https://github.com/jnunemaker/httparty/pull/585)
## 0.16.1
* [Parse content with application/hal+json content type as JSON](https://github.com/jnunemaker/httparty/pull/573)
* [Convert objects to string when concatenating in multipart stuff](https://github.com/jnunemaker/httparty/pull/575)
* [Fix multipart to set its header even when other headers are provided](https://github.com/jnunemaker/httparty/pull/576)
## 0.16.0
* [Add multipart support](https://github.com/jnunemaker/httparty/pull/569)
## 0.15.7
Fixed
* [Add Response#pretty_print | Restore documented behavior](https://github.com/jnunemaker/httparty/pull/570)
* [Add ability to parse response from JSONAPI ](https://github.com/jnunemaker/httparty/pull/553)
## 0.15.6
Fixed
* [Encoding and content type stuff](https://github.com/jnunemaker/httparty/pull/543)
## 0.15.5
Fixed
* [Use non-destructive gsub](https://github.com/jnunemaker/httparty/pull/540)
## 0.15.4
Fixed
* Prevent gsub errors with different encodings.
* Prevent passing nil to encode_body.
## 0.15.3
Fixed
* [Fix processing nil body for HEAD requests](https://github.com/jnunemaker/httparty/pull/530).
* Add missing require to headers.rb (33439a8).
## 0.15.2
Fixed
* Remove symlink from specs. It was reportedly still getting bundled with gem.
## 0.15.1
Fixed
* Stop including test files in gem. Fixes installation issues on windows due to symlink in spec dir.
## 0.15.0
Breaking Changes
* require Ruby >= 2.0.0
Fixed
* [fix numerous bugs](https://github.com/jnunemaker/httparty/pull/513)
* [handle utf-8 bom for json parsing](https://github.com/jnunemaker/httparty/pull/520)
* [do not overwrite default headers unless specified](https://github.com/jnunemaker/httparty/pull/518)
## 0.14.0
Breaking Changes
* None
Added
* [added status predicate methods to Response#respond_to?](https://github.com/jnunemaker/httparty/pull/482)
* [support for MKCOL method](https://github.com/jnunemaker/httparty/pull/465)
* one fewer dependency: [remove json gem from gemspec](https://github.com/jnunemaker/httparty/pull/464)
* [optional raising exception on certain status codes](https://github.com/jnunemaker/httparty/pull/455)
Fixed
* [allow empty array to be used as param](https://github.com/jnunemaker/httparty/pull/477)
* [stop mutating cookie hash](https://github.com/jnunemaker/httparty/pull/460)
## 0.13.7 aka "party not as hard"
* remove post install emoji as it caused installation issues for some people
## 0.13.6
* avoid calling String#strip on invalid Strings
* preserve request method on 307 and 308 redirects
* output version with --version for command line bin
* maintain head request method across redirects by default
* add support for RFC2617 MD5-sess algorithm type
* add party popper emoji to post install message
## 0.13.5
* allow setting a custom URI adapter
## 0.13.4
* correct redirect url for redirect paths without leading slash
* remove core_extensions.rb as backwards compat for ruby 1.8 not needed
* replace URI.encode with ERB::Util.url_encode
* allow the response to be tapped
## 0.13.3
* minor improvement
* added option to allow for streaming large files without loading them into memory (672cdae)
## 0.13.2
* minor improvement
* [Set correct path on redirect to filename](https://github.com/jnunemaker/httparty/pull/337)
* ensure logger works with curl format
## 0.13.1 2014-04-08
* new
* [Added ability to specify a body_stream in HttpRequest](https://github.com/jnunemaker/httparty/pull/275)
* [Added read_timeout and open_timeout options](https://github.com/jnunemaker/httparty/pull/278)
* change
* [Initialize HTTParty requests with an URI object and a String](https://github.com/jnunemaker/httparty/pull/274)
* minor improvement
* [Add stackexchange API example](https://github.com/jnunemaker/httparty/pull/280)
## 0.13.0 2014-02-14
* new
* [Add CSV support](https://github.com/jnunemaker/httparty/pull/269)
* [Allows PKCS12 client certificates](https://github.com/jnunemaker/httparty/pull/246)
* bug fix
* [Digest auth no longer fails when multiple headers are sent by the server](https://github.com/jnunemaker/httparty/pull/272)
* [Use 'Basement.copy' when calling 'HTTParty.copy'](https://github.com/jnunemaker/httparty/pull/268)
* [No longer appends ampersand when queries are embedded in paths](https://github.com/jnunemaker/httparty/pull/252)
* change
* [Merge - instead of overwrite - default headers with request provided headers](https://github.com/jnunemaker/httparty/pull/270)
* [Modernize respond_to implementations to support second param](https://github.com/jnunemaker/httparty/pull/264)
* [Sort query parameters by key before processing](https://github.com/jnunemaker/httparty/pull/245)
* minor improvement
* [Add HTTParty::Error base class](https://github.com/jnunemaker/httparty/pull/260)
## 0.12.0 2013-10-10
* new
* [Added initial logging support](https://github.com/jnunemaker/httparty/pull/243)
* [Add support for local host and port binding](https://github.com/jnunemaker/httparty/pull/238)
* [content_type_charset_support](https://github.com/jnunemaker/httparty/commit/82e351f0904e8ecc856015ff2854698a2ca47fbc)
* bug fix
* [No longer attempt to decompress the body on HEAD requests](https://github.com/jnunemaker/httparty/commit/f2b8cc3d49e0e9363d7054b14f30c340d7b8e7f1)
* [Adding java check in aliasing of multiple choices](https://github.com/jnunemaker/httparty/pull/204/commits)
* change
* [MIME-type files of javascript are returned as a string instead of JSON](https://github.com/jnunemaker/httparty/pull/239)
* [Made SSL connections use the system certificate store by default](https://github.com/jnunemaker/httparty/pull/226)
* [Do not pass proxy options to Net::HTTP connection if not specified](https://github.com/jnunemaker/httparty/pull/222)
* [Replace multi_json with stdlib json](https://github.com/jnunemaker/httparty/pull/214)
* [Require Ruby >= 1.9.3]
* [Response returns array of returned cookie strings](https://github.com/jnunemaker/httparty/pull/218)
* [Allow '=' within value of a cookie]
* minor improvements
* [Improve documentation of ssl_ca_file, ssl_ca_path](https://github.com/jnunemaker/httparty/pull/223)
* [Fix example URLs](https://github.com/jnunemaker/httparty/pull/232)
## 0.11.0 2013-04-10
* new
* [Add COPY http request handling](https://github.com/jnunemaker/httparty/pull/190)
* [Ruby 2.0 tests](https://github.com/jnunemaker/httparty/pull/194)
* [Ruby >= 2.0.0 support both multiple_choice? and multiple_choices?]
* bug fix
* [Maintain blocks passed to 'perform' in redirects](https://github.com/jnunemaker/httparty/pull/191)
* [Fixed nc value being quoted, this was against spec](https://github.com/jnunemaker/httparty/pull/196)
* [Request#uri no longer duplicates non-relative-path params](https://github.com/jnunemaker/httparty/pull/189)
* change
* [Client-side-only cookie attributes are removed: case-insensitive](https://github.com/jnunemaker/httparty/pull/188)
## 0.10.2 2013-01-26
* bug fix
* [hash_conversions misnamed variable](https://github.com/jnunemaker/httparty/pull/187)
## 0.10.1 2013-01-26
* new
* [Added support for MOVE requests](https://github.com/jnunemaker/httparty/pull/183)
* [Bump multi xml version](https://github.com/jnunemaker/httparty/pull/181)
## 0.10.0 2013-01-10
* changes
* removed yaml support because of security risk (see rails yaml issues)
## 0.9.0 2012-09-07
* new
* [support for connection adapters](https://github.com/jnunemaker/httparty/pull/157)
* [allow ssl_version on ruby 1.9](https://github.com/jnunemaker/httparty/pull/159)
* bug fixes
* [don't treat port 4430 as ssl](https://github.com/jnunemaker/httparty/commit/a296b1c97f83d7dcc6ef85720a43664c265685ac)
* [deep clone default options](https://github.com/jnunemaker/httparty/commit/f74227d30f9389b4b23a888c9af49fb9b8248e1f)
* a few net digest auth fixes
## 0.8.3 2012-04-21
* new
* [lazy parsing of responses](https://github.com/jnunemaker/httparty/commit/9fd5259c8dab00e426082b66af44ede2c9068f45)
* [add support for PATCH requests](https://github.com/jnunemaker/httparty/commit/7ab6641e37a9e31517e46f6124f38c615395d38a)
* bug fixes
* [subclasses no longer override superclass options](https://github.com/jnunemaker/httparty/commit/682af8fbf672e7b3009e650da776c85cdfe78d39)
## 0.8.2 2012-04-12
* new
* add -r to make CLI return failure code if status >= 400
* allow blank username from CLI
* bug fixes
* return nil for null body
* automatically deflate responses with a Content-Encoding: x-gzip header
* Do not HEAD on POST request with digest authentication
* add support for proxy authentication
* fix posting data with CLI
* require rexml/document if xml format from CLI
* support for fragmented responses
## 0.8.1 2011-10-05
* bug fixes
* content-encoding header should be removed when automatically inflating the body
## 0.8.0 2011-09-13
* new
* switch to multi json/xml for parsing by default
* bug fixes
* fix redirects to relative uri's
## 0.7.8 2011-06-06
* bug fix
* Make response honor respond to
* net http timeout can also be a float
## 0.7.7 2011-04-16
* bug fix
* Fix NoMethodError when using the NON_RAILS_QUERY_STRING_NORMALIZER with a hash whose key is a symbol and value is nil
## 0.7.5 2011-04-16
* bug fix
* caused issue with latest rubygems
## 0.7.4 2011-02-13
* bug fixes
* Set VERIFY_NONE when using https. Ruby 1.9.2 no longer sets this for us. gh-67
## 0.7.3 2011-01-20
* bug fixes
* Fix digest auth for unspecified quality of protection (bjoernalbers, mtrudel, dwo)
## 0.7.2 2011-01-20
* bug fixes
* Fix gem dependencies
## 0.7.1 2011-01-19
* bug fixes
* Fix uninitialized constant HTTParty::Response::Net in 1.9.2 (cap10morgan)
* Other fixes for 1.9.2, full suite still fails (cap10morgan)
## 0.7.0 2011-01-18
* minor enhancements
* Added query methods for HTTP status codes, i.e. response.success?
response.created? (thanks citizenparker)
* Added support for ssl_ca_file and ssl_ca_path (dlitz)
* Allow custom query string normalization. gh-8
* Unlock private keys with password (freerange)
* Added high level request documentation (phildarnowsky)
* Added basic post example (pbuckley)
* Response object has access to its corresponding request object
* Added example of siginin into tripit.com
* Added option to follow redirects (rkj). gh-56
* bug fixes
* Fixed superclass mismatch exception while running tests
(thanks dlitz http://github.com/dlitz/httparty/commit/48224f0615b32133afcff4718ad426df7a4b401b)
## 0.6.1 2010-07-07
* minor enhancements
* updated to crack 0.1.8
* bug fixes
* subclasses always merge into the parent's default_options and
default_cookies (l4rk).
* subclasses play nicely with grand parents. gh-49
## 0.6.0 2010-06-13
* major enhancements
* Digest Auth (bartiaco, sbecker, gilles, and aaronrussell)
* Maintain HTTP method across redirects (bartiaco and sbecker)
* HTTParty::Response#response returns the Net::HTTPResponse object
* HTTParty::Response#headers returns a HTTParty::Response::Headers object
which quacks like a Hash + Net::HTTPHeader. The #headers method continues
to be backwards-compatible with the old Hash return value but may become
deprecated in the future.
* minor enhancements
* Update crack requirement to version 0.1.7
You may still get a warning because Crack's version constant is out of date
* Timeout option can be set for all requests using HTTParty.default_timeout (taazza)
* Closed #38 "headers hash should downcase keys so canonical header name can be used"
* Closed #40 "Gzip response" wherein gziped and deflated responses are
automatically inflated. (carsonmcdonald)
## 0.5.2 2010-01-31
* minor enhancements
* Update crack requirement to version 0.1.6
## 0.5.1 2010-01-30
* bug fixes
* Handle 304 response correctly by returning the HTTParty::Response object instead of redirecting (seth and hellvinz)
* Only redirect 300 responses if the header contains a Location
* Don't append empty query strings to the uri. Closes #31
* When no_follow is enabled, only raise the RedirectionTooDeep exception when a response tries redirecting. Closes #28
* major enhancements
* Removed rubygems dependency. I suggest adding rubygems to RUBYOPT if this causes problems for you.
$ export RUBYOPT='rubygems'
* HTTParty#debug_output prints debugging information for the current request (iwarshak)
* HTTParty#no_follow now available as a class-level option. Sets whether or not to follow redirects.
* minor enhancements
* HTTParty::VERSION now available
* Update crack requirement to version 0.1.5
## 0.5.0 2009-12-07
* bug fixes
* inheritable attributes no longer mutable by subclasses (yyyc514)
* namespace BasicObject within HTTParty to avoid class name collisions (eric)
* major enhancements
* Custom Parsers via class or proc
* Deprecation warning on HTTParty::AllowedFormats
moved to HTTParty::Parser::SupportedFormats
* minor enhancements
* Curl inspired output when using the binary in verbose mode (alexvollmer)
* raise UnsupportedURIScheme when scheme is not HTTP or HTTPS (djspinmonkey)
* Allow SSL for ports other than 443 when scheme is HTTPS (stefankroes)
* Accept PEM certificates via HTTParty#pem (chrislo)
* Support HEAD and OPTION verbs (grempe)
* Verify SSL certificates when providing a PEM file (collectiveidea/danielmorrison)
## 0.4.5 2009-09-12
* bug fixes
* Fixed class-level headers overwritten by cookie management code. Closes #19
* Fixed "superclass mismatch for class BlankSlate" error. Closes #20
* Fixed reading files as post data from the command line (vesan)
* minor enhancements
* Timeout option added; will raise a Timeout::Error after the timeout has elapsed (attack). Closes #17
HTTParty.get "http://github.com", timeout: 1
* Building gem with Jeweler
## 0.4.4 2009-07-19
* 2 minor update
* :query no longer sets form data. Use body and set content type to application/x-www-form-urlencoded if you need it. :query was wrong for that.
* Fixed a bug in the cookies class method that caused cookies to be forgotten after the first request.
* Also, some general cleanup of tests and such.
## 0.4.3 2009-04-23
* 1 minor update
* added message to the response object
## 0.4.2 2009-03-30
* 2 minor changes
* response code now returns an integer instead of a string (jqr)
* rubyforge project setup for crack so i'm now depending on that instead of jnunemaker-crack
## 0.4.1 2009-03-29
* 1 minor fix
* gem 'jnunemaker-crack' instead of gem 'crack'
## 0.4.0 2009-03-29
* 1 minor change
* Switched xml and json parsing to crack (same code as before just moved to gem for easier reuse in other projects)
## 0.3.1 2009-02-10
* 1 minor fix, 1 minor enhancement
* Fixed unescaping umlauts (siebertm)
* Added yaml response parsing (Miha Filej)
## 0.3.0 2009-01-31
* 1 major enhancement, 1 bug fix
* JSON gem no longer a requirement. It was conflicting with rails json stuff so I just stole ActiveSupport's json decoding and bundled it with HTTParty.
* Fixed bug where query strings were being duplicated on redirects
* Added a bunch of specs and moved some code around.
## 0.2.10 2009-01-29
* 1 minor enhancement
* Made encoding on query parameters treat everything except URI::PATTERN::UNRESERVED as UNSAFE to force encoding of '+' character (Julian Russell)
## 0.2.9 2009-01-29
* 3 minor enhancements
* Added a 'headers' accessor to the response with a hash of any HTTP headers. (Don Peterson)
* Add support for a ":cookies" option to be used at the class level, or as an option on any individual call. It should be passed a hash, which will be converted to the proper format and added to the request headers when the call is made. (Don Peterson)
* Refactored several specs and added a full suite of cucumber features (Don Peterson)
## 0.2.8 2009-01-28
* 1 major fix
* fixed major bug with response where it wouldn't iterate or really work at all with parsed responses
## 0.2.7 2009-01-28
* 2 minor fixes, 2 minor enhancements, 2 major enhancements
* fixed undefined method add_node for nil class error that occasionally happened (juliocesar)
* Handle nil or unexpected values better when typecasting. (Brian Landau)
* More robust handling of mime types (Alex Vollmer)
* Fixed support for specifying headers and added support for basic auth to CLI. (Alex Vollmer)
* Added first class response object that includes original body and status code (Alex Vollmer)
* Now parsing all response types as some non-200 responses provide important information, this means no more exception raising (Alex Vollmer)
## 0.2.6 2009-01-05
* 1 minor bug fix
* added explicit require of time as Time#parse failed outside of rails (willcodeforfoo)
## 0.2.5 2009-01-05
* 1 major enhancement
* Add command line interface to HTTParty (Alex Vollmer)
## 0.2.4 2008-12-23
* 1 bug fix
* Fixed that mimetype detection was failing if no mimetype was returned from service (skippy)
## 0.2.3 2008-12-23
* 1 bug fix
* Fixed typecasting class variable naming issue
## 0.2.2 2008-12-08
* 1 bug fix
* Added the missing core extension hash method to_xml_attributes
## 0.2.1 2008-12-08
* 1 bug fix
* Fixed that HTTParty was borking ActiveSupport and as such Rails (thanks to Rob Sanheim)
## 0.2.0 2008-12-07
* 1 major enhancement
* Removed ActiveSupport as a dependency. Now requires json gem for json deserialization and uses an included class to do the xml parsing.
## 0.1.8 2008-11-30
* 3 major enhancements
* Moved base_uri normalization into request class and out of httparty module, fixing
the problem where base_uri was not always being normalized.
* Stupid simple support for HTTParty.get/post/put/delete. (jqr)
* Switched gem management to Echoe from newgem.
## 0.1.7 2008-11-30
* 1 major enhancement
* fixed multiple class definitions overriding each others options
## 0.1.6 2008-11-26
* 1 major enhancement
* now passing :query to set_form_data if post request to avoid content length errors
## 0.1.5 2008-11-14
* 2 major enhancements
* Refactored send request method out into its own object.
* Added :html format if you just want to do that.
## 0.1.4 2008-11-08
* 3 major enhancements:
* Removed some cruft
* Added ability to follow redirects automatically and turn that off (Alex Vollmer)
## 0.1.3 2008-08-22
* 3 major enhancements:
* Added http_proxy key for setting proxy server and port (francxk@gmail.com)
* Now raises exception when http error occurs (francxk@gmail.com)
* Changed auto format detection from file extension to response content type (Jay Pignata)
## 0.1.2 2008-08-09
* 1 major enhancement:
* default_params were not being appended to query string if option[:query] was blank
## 0.1.1 2008-07-30
* 2 major enhancement:
* Added :basic_auth key for options when making a request
* :query and :body both now work with query string or hash
## 0.1.0 2008-07-27
* 1 major enhancement:
* Initial release
httparty-0.18.1/Gemfile 0000664 0000000 0000000 00000000556 13670224415 0014765 0 ustar 00root root 0000000 0000000 source 'https://rubygems.org'
gemspec
gem 'rake'
gem 'mongrel', '1.2.0.pre2'
group :development do
gem 'guard'
gem 'guard-rspec'
gem 'guard-bundler'
end
group :test do
gem 'rspec', '~> 3.4'
gem 'simplecov', require: false
gem 'aruba'
gem 'cucumber', '~> 2.3'
gem 'webmock'
gem 'addressable'
end
group :development, :test do
gem 'pry'
end
httparty-0.18.1/Guardfile 0000664 0000000 0000000 00000000514 13670224415 0015311 0 ustar 00root root 0000000 0000000 rspec_options = {
version: 1,
all_after_pass: false,
all_on_start: false
}
guard 'rspec', rspec_options do
watch(%r{^spec/.+_spec\.rb$})
watch(%r{^lib/(.+)\.rb$}) { |m| "spec/#{m[1]}_spec.rb" }
watch('spec/spec_helper.rb') { "spec" }
end
guard 'bundler' do
watch('Gemfile')
watch(/^.+\.gemspec/)
end
httparty-0.18.1/MIT-LICENSE 0000664 0000000 0000000 00000002041 13670224415 0015115 0 ustar 00root root 0000000 0000000 Copyright (c) 2008 John Nunemaker
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. httparty-0.18.1/README.md 0000664 0000000 0000000 00000004554 13670224415 0014753 0 ustar 00root root 0000000 0000000 # httparty
[](https://travis-ci.org/jnunemaker/httparty)
Makes http fun again! Ain't no party like a httparty, because a httparty don't stop.
## Install
```
gem install httparty
```
## Requirements
* Ruby 2.0.0 or higher
* multi_xml
* You like to party!
## Examples
```ruby
# Use the class methods to get down to business quickly
response = HTTParty.get('http://api.stackexchange.com/2.2/questions?site=stackoverflow')
puts response.body, response.code, response.message, response.headers.inspect
# Or wrap things up in your own class
class StackExchange
include HTTParty
base_uri 'api.stackexchange.com'
def initialize(service, page)
@options = { query: { site: service, page: page } }
end
def questions
self.class.get("/2.2/questions", @options)
end
def users
self.class.get("/2.2/users", @options)
end
end
stack_exchange = StackExchange.new("stackoverflow", 1)
puts stack_exchange.questions
puts stack_exchange.users
```
See the [examples directory](http://github.com/jnunemaker/httparty/tree/master/examples) for even more goodies.
## Command Line Interface
httparty also includes the executable `httparty` which can be
used to query web services and examine the resulting output. By default
it will output the response as a pretty-printed Ruby object (useful for
grokking the structure of output). This can also be overridden to output
formatted XML or JSON. Execute `httparty --help` for all the
options. Below is an example of how easy it is.
```
httparty "https://api.stackexchange.com/2.2/questions?site=stackoverflow"
```
## Help and Docs
* [Docs](https://github.com/jnunemaker/httparty/tree/master/docs)
* https://groups.google.com/forum/#!forum/httparty-gem
* https://www.rubydoc.info/github/jnunemaker/httparty
* http://stackoverflow.com/questions/tagged/httparty
## Contributing
* Fork the project.
* Run `bundle`
* Run `bundle exec rake`
* Make your feature addition or bug fix.
* Add tests for it. This is important so I don't break it in a future version unintentionally.
* Run `bundle exec rake` (No, REALLY :))
* Commit, do not mess with rakefile, version, or history. (if you want to have your own version, that is fine but bump version in a commit by itself in another branch so I can ignore when I pull)
* Send me a pull request. Bonus points for topic branches.
httparty-0.18.1/Rakefile 0000664 0000000 0000000 00000000303 13670224415 0015125 0 ustar 00root root 0000000 0000000 begin
require 'rspec/core/rake_task'
RSpec::Core::RakeTask.new(:spec)
rescue LoadError
end
require 'cucumber/rake/task'
Cucumber::Rake::Task.new(:features)
task default: [:spec, :features]
httparty-0.18.1/bin/ 0000775 0000000 0000000 00000000000 13670224415 0014234 5 ustar 00root root 0000000 0000000 httparty-0.18.1/bin/httparty 0000775 0000000 0000000 00000006026 13670224415 0016045 0 ustar 00root root 0000000 0000000 #!/usr/bin/env ruby
require "optparse"
require "pp"
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), "/../lib"))
require "httparty"
opts = {
action: :get,
headers: {},
verbose: false
}
OptionParser.new do |o|
o.banner = "USAGE: #{$PROGRAM_NAME} [options] [url]"
o.on("-f",
"--format [FORMAT]",
"Output format to use instead of pretty-print ruby: " \
"plain, csv, json or xml") do |f|
opts[:output_format] = f.downcase.to_sym
end
o.on("-a",
"--action [ACTION]",
"HTTP action: get (default), post, put, delete, head, or options") do |a|
opts[:action] = a.downcase.to_sym
end
o.on("-d",
"--data [BODY]",
"Data to put in request body (prefix with '@' for file)") do |d|
if d =~ /^@/
opts[:body] = open(d[1..-1]).read
else
opts[:body] = d
end
end
o.on("-H", "--header [NAME:VALUE]", "Additional HTTP headers in NAME:VALUE form") do |h|
abort "Invalid header specification, should be Name:Value" unless h =~ /.+:.+/
name, value = h.split(':')
opts[:headers][name.strip] = value.strip
end
o.on("-v", "--verbose", "If set, print verbose output") do |v|
opts[:verbose] = true
end
o.on("-u", "--user [CREDS]", "Use basic authentication. Value should be user:password") do |u|
abort "Invalid credentials format. Must be user:password" unless u =~ /.*:.+/
user, password = u.split(':')
opts[:basic_auth] = { username: user, password: password }
end
o.on("-r", "--response-code", "Command fails if response code >= 400") do
opts[:response_code] = true
end
o.on("-h", "--help", "Show help documentation") do |h|
puts o
exit
end
o.on("--version", "Show HTTParty version") do |ver|
puts "Version: #{HTTParty::VERSION}"
exit
end
end.parse!
if ARGV.empty?
STDERR.puts "You need to provide a URL"
STDERR.puts "USAGE: #{$PROGRAM_NAME} [options] [url]"
end
def dump_headers(response)
resp_type = Net::HTTPResponse::CODE_TO_OBJ[response.code.to_s]
puts "#{response.code} #{resp_type.to_s.sub(/^Net::HTTP/, '')}"
response.headers.each do |n, v|
puts "#{n}: #{v}"
end
puts
end
if opts[:verbose]
puts "#{opts[:action].to_s.upcase} #{ARGV.first}"
opts[:headers].each do |n, v|
puts "#{n}: #{v}"
end
puts
end
response = HTTParty.send(opts[:action], ARGV.first, opts)
if opts[:output_format].nil?
dump_headers(response) if opts[:verbose]
pp response
else
print_format = opts[:output_format]
dump_headers(response) if opts[:verbose]
case opts[:output_format]
when :json
begin
require 'json'
puts JSON.pretty_generate(response.parsed_response)
rescue LoadError
puts YAML.dump(response)
rescue JSON::JSONError
puts response.inspect
end
when :xml
require 'rexml/document'
REXML::Document.new(response.body).write(STDOUT, 2)
puts
when :csv
require 'csv'
puts CSV.parse(response.body).map(&:to_s)
else
puts response
end
end
exit false if opts[:response_code] && response.code >= 400
httparty-0.18.1/cucumber.yml 0000664 0000000 0000000 00000000044 13670224415 0016012 0 ustar 00root root 0000000 0000000 default: features --format progress
httparty-0.18.1/docs/ 0000775 0000000 0000000 00000000000 13670224415 0014414 5 ustar 00root root 0000000 0000000 httparty-0.18.1/docs/README.md 0000664 0000000 0000000 00000004452 13670224415 0015700 0 ustar 00root root 0000000 0000000 # httparty
Makes http fun again!
## Table of contents
- [Parsing JSON](#parsing-json)
- [Working with SSL](#working-with-ssl)
## Parsing JSON
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:
```ruby
response = HTTParty.get('http://example.com', format: :plain)
JSON.parse response, symbolize_names: true
```
## Working with SSL
You can use this guide to work with SSL certificates.
#### Using `pem` option
```ruby
# Use this example if you are using a pem file
class Client
include HTTParty
base_uri "https://example.com"
pem File.read("#{File.expand_path('.')}/path/to/certs/cert.pem"), "123456"
end
```
#### Using `pkcs12` option
```ruby
# Use this example if you are using a pkcs12 file
class Client
include HTTParty
base_uri "https://example.com"
pkcs12 File.read("#{File.expand_path('.')}/path/to/certs/cert.p12"), "123456"
end
```
#### Using `ssl_ca_file` option
```ruby
# Use this example if you are using a pkcs12 file
class Client
include HTTParty
base_uri "https://example.com"
ssl_ca_file "#{File.expand_path('.')}/path/to/certs/cert.pem"
end
```
#### Using `ssl_ca_path` option
```ruby
# Use this example if you are using a pkcs12 file
class Client
include HTTParty
base_uri "https://example.com"
ssl_ca_path '/path/to/certs'
end
```
You can also include this options with the call:
```ruby
class Client
include HTTParty
base_uri "https://example.com"
def self.fetch
get("/resources", pem: File.read("#{File.expand_path('.')}/path/to/certs/cert.pem"), pem_password: "123456")
end
end
```
### Avoid SSL verification
In some cases you may want to skip SSL verification, because the entity that issue the certificate is not a valid one, but you still want to work with it. You can achieve this through:
```ruby
# Skips SSL certificate verification
class Client
include HTTParty
base_uri "https://example.com"
pem File.read("#{File.expand_path('.')}/path/to/certs/cert.pem"), "123456"
def self.fetch
get("/resources", verify: false)
# You can also use something like:
# get("resources", verify_peer: false)
end
end
```
httparty-0.18.1/examples/ 0000775 0000000 0000000 00000000000 13670224415 0015302 5 ustar 00root root 0000000 0000000 httparty-0.18.1/examples/README.md 0000664 0000000 0000000 00000004656 13670224415 0016574 0 ustar 00root root 0000000 0000000 ## Examples
* [Amazon Book Search](aaws.rb)
* Httparty included into poro class
* Uses `get` requests
* Transforms query params to uppercased params
* [Google Search](google.rb)
* Httparty included into poro class
* Uses `get` requests
* [Crack Custom Parser](crack.rb)
* Creates a custom parser for XML using crack gem
* Uses `get` request
* [Create HTML Nokogiri parser](nokogiri_html_parser.rb)
* Adds Html as a format
* passed the body of request to Nokogiri
* [More Custom Parsers](custom_parsers.rb)
* Create an additional parser for atom or make it the ONLY parser
* [Basic Auth, Delicious](delicious.rb)
* Basic Auth, shows how to merge those into options
* Uses `get` requests
* [Passing Headers, User Agent](headers_and_user_agents.rb)
* Use the class method of Httparty
* Pass the User-Agent in the headers
* Uses `get` requests
* [Basic Post Request](basic.rb)
* Httparty included into poro class
* Uses `post` requests
* [Access Rubyurl Shortener](rubyurl.rb)
* Httparty included into poro class
* Uses `post` requests
* [Add a custom log file](logging.rb)
* create a log file and have httparty log requests
* [Accessing StackExchange](stackexchange.rb)
* Httparty included into poro class
* Creates methods for different endpoints
* Uses `get` requests
* [Accessing Tripit](tripit_sign_in.rb)
* Httparty included into poro class
* Example of using `debug_output` to see headers/urls passed
* Getting and using Cookies
* Uses `get` requests
* [Accessing Twitter](twitter.rb)
* Httparty included into poro class
* Basic Auth
* Loads settings from a config file
* Uses `get` requests
* Uses `post` requests
* [Accessing WhoIsMyRep](whoismyrep.rb)
* Httparty included into poro class
* Uses `get` requests
* Two ways to pass params to get, inline on the url or in query hash
* [Rescue Json Error](rescue_json.rb)
* Rescue errors due to parsing response
* [Download file using stream mode](stream_download.rb)
* Uses `get` requests
* Uses `stream_body` mode
* Download file without using the memory
* [Microsoft graph](microsoft_graph.rb)
* Basic Auth
* Uses `post` requests
* Uses multipart
* [Multipart](multipart.rb)
* Multipart data upload _(with and without file)_
* [Uploading File](body_stream.rb)
* Uses `body_stream` to upload file
* [Accessing x509 Peer Certificate](peer_cert.rb)
* Provides access to the server's TLS certificate
httparty-0.18.1/examples/aaws.rb 0000664 0000000 0000000 00000002013 13670224415 0016556 0 ustar 00root root 0000000 0000000 require 'rubygems'
require 'active_support'
dir = File.expand_path(File.join(File.dirname(__FILE__), '..', 'lib'))
require File.join(dir, 'httparty')
require 'pp'
config = YAML.load(File.read(File.join(ENV['HOME'], '.aaws')))
module AAWS
class Book
include HTTParty
base_uri 'http://ecs.amazonaws.com'
default_params Service: 'AWSECommerceService', Operation: 'ItemSearch', SearchIndex: 'Books'
def initialize(key)
self.class.default_params AWSAccessKeyId: key
end
def search(options = {})
raise ArgumentError, 'You must search for something' if options[:query].blank?
# amazon uses nasty camelized query params
options[:query] = options[:query].inject({}) { |h, q| h[q[0].to_s.camelize] = q[1]; h }
# make a request and return the items (NOTE: this doesn't handle errors at this point)
self.class.get('/onca/xml', options)['ItemSearchResponse']['Items']
end
end
end
aaws = AAWS::Book.new(config[:access_key])
pp aaws.search(query: { title: 'Ruby On Rails' })
httparty-0.18.1/examples/basic.rb 0000664 0000000 0000000 00000001447 13670224415 0016716 0 ustar 00root root 0000000 0000000 dir = File.expand_path(File.join(File.dirname(__FILE__), '..', 'lib'))
require File.join(dir, 'httparty')
require 'pp'
# You can also use post, put, delete, head, options in the same fashion
response = HTTParty.get('https://api.stackexchange.com/2.2/questions?site=stackoverflow')
puts response.body, response.code, response.message, response.headers.inspect
# An example post to a minimal rails app in the development environment
# Note that "skip_before_filter :verify_authenticity_token" must be set in the
# "pears" controller for this example
class Partay
include HTTParty
base_uri 'http://localhost:3000'
end
options = {
body: {
pear: { # your resource
foo: '123', # your columns/data
bar: 'second',
baz: 'last thing'
}
}
}
pp Partay.post('/pears.xml', options)
httparty-0.18.1/examples/body_stream.rb 0000664 0000000 0000000 00000000452 13670224415 0020140 0 ustar 00root root 0000000 0000000 # To upload file to a server use :body_stream
HTTParty.put(
'http://localhost:3000/train',
body_stream: File.open('sample_configs/config_train_server_md.yml', 'r')
)
# Actually, it works with any IO object
HTTParty.put(
'http://localhost:3000/train',
body_stream: StringIO.new('foo')
)
httparty-0.18.1/examples/crack.rb 0000664 0000000 0000000 00000000654 13670224415 0016717 0 ustar 00root root 0000000 0000000 require 'rubygems'
require 'crack'
dir = File.expand_path(File.join(File.dirname(__FILE__), '..', 'lib'))
require File.join(dir, 'httparty')
require 'pp'
class Rep
include HTTParty
parser(
proc do |body, format|
Crack::XML.parse(body)
end
)
end
pp Rep.get('http://whoismyrepresentative.com/getall_mems.php?zip=46544')
pp Rep.get('http://whoismyrepresentative.com/getall_mems.php', query: { zip: 46544 })
httparty-0.18.1/examples/custom_parsers.rb 0000664 0000000 0000000 00000002202 13670224415 0020674 0 ustar 00root root 0000000 0000000 dir = File.expand_path(File.join(File.dirname(__FILE__), '..', 'lib'))
require File.join(dir, 'httparty')
require 'pp'
class ParseAtom
include HTTParty
# Support Atom along with the default parsers: xml, json, etc.
class Parser::Atom < HTTParty::Parser
SupportedFormats.merge!({"application/atom+xml" => :atom})
protected
# perform atom parsing on body
def atom
body.to_atom
end
end
parser Parser::Atom
end
class OnlyParseAtom
include HTTParty
# Only support Atom
class Parser::OnlyAtom < HTTParty::Parser
SupportedFormats = { "application/atom+xml" => :atom }
protected
# perform atom parsing on body
def atom
body.to_atom
end
end
parser Parser::OnlyAtom
end
class SkipParsing
include HTTParty
# Parse the response body however you like
class Parser::Simple < HTTParty::Parser
def parse
body
end
end
parser Parser::Simple
end
class AdHocParsing
include HTTParty
parser(
proc do |body, format|
case format
when :json
body.to_json
when :xml
body.to_xml
else
body
end
end
)
end
httparty-0.18.1/examples/delicious.rb 0000664 0000000 0000000 00000002223 13670224415 0017606 0 ustar 00root root 0000000 0000000 dir = File.expand_path(File.join(File.dirname(__FILE__), '..', 'lib'))
require File.join(dir, 'httparty')
require 'pp'
config = YAML.load(File.read(File.join(ENV['HOME'], '.delicious')))
class Delicious
include HTTParty
base_uri 'https://api.del.icio.us/v1'
def initialize(u, p)
@auth = { username: u, password: p }
end
# query params that filter the posts are:
# tag (optional). Filter by this tag.
# dt (optional). Filter by this date (CCYY-MM-DDThh:mm:ssZ).
# url (optional). Filter by this url.
# ie: posts(query: {tag: 'ruby'})
def posts(options = {})
options.merge!({ basic_auth: @auth })
self.class.get('/posts/get', options)
end
# query params that filter the posts are:
# tag (optional). Filter by this tag.
# count (optional). Number of items to retrieve (Default:15, Maximum:100).
def recent(options = {})
options.merge!({ basic_auth: @auth })
self.class.get('/posts/recent', options)
end
end
delicious = Delicious.new(config['username'], config['password'])
pp delicious.posts(query: { tag: 'ruby' })
pp delicious.recent
delicious.recent['posts']['post'].each { |post| puts post['href'] }
httparty-0.18.1/examples/google.rb 0000664 0000000 0000000 00000000602 13670224415 0017101 0 ustar 00root root 0000000 0000000 dir = File.expand_path(File.join(File.dirname(__FILE__), '..', 'lib'))
require File.join(dir, 'httparty')
require 'pp'
class Google
include HTTParty
format :html
end
# google.com redirects to www.google.com so this is live test for redirection
pp Google.get('http://google.com')
puts '', '*' * 70, ''
# check that ssl is requesting right
pp Google.get('https://www.google.com')
httparty-0.18.1/examples/headers_and_user_agents.rb 0000664 0000000 0000000 00000000702 13670224415 0022462 0 ustar 00root root 0000000 0000000 # 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.
dir = File.expand_path(File.join(File.dirname(__FILE__), '..', 'lib'))
require File.join(dir, 'httparty')
require 'pp'
response = HTTParty.get('http://example.com', {
headers: {"User-Agent" => "Httparty"},
debug_output: STDOUT, # To show that User-Agent is Httparty
})
httparty-0.18.1/examples/logging.rb 0000664 0000000 0000000 00000001742 13670224415 0017261 0 ustar 00root root 0000000 0000000 dir = File.expand_path(File.join(File.dirname(__FILE__), '..', 'lib'))
require File.join(dir, 'httparty')
require 'logger'
require 'pp'
my_logger = Logger.new STDOUT
my_logger.info "Logging can be used on the main HTTParty class. It logs redirects too."
HTTParty.get "http://google.com", logger: my_logger
my_logger.info '*' * 70
my_logger.info "It can be used also on a custom class."
class Google
include HTTParty
logger ::Logger.new STDOUT
end
Google.get "http://google.com"
my_logger.info '*' * 70
my_logger.info "The default formatter is :apache. The :curl formatter can also be used."
my_logger.info "You can tell which method to call on the logger too. It is info by default."
HTTParty.get "http://google.com", logger: my_logger, log_level: :debug, log_format: :curl
my_logger.info '*' * 70
my_logger.info "These configs are also available on custom classes."
class Google
include HTTParty
logger ::Logger.new(STDOUT), :debug, :curl
end
Google.get "http://google.com"
httparty-0.18.1/examples/microsoft_graph.rb 0000664 0000000 0000000 00000003022 13670224415 0021012 0 ustar 00root root 0000000 0000000 require 'httparty'
class MicrosoftGraph
MS_BASE_URL = "https://login.microsoftonline.com".freeze
TOKEN_REQUEST_PATH = "oauth2/v2.0/token".freeze
def initialize(tenant_id)
@tenant_id = tenant_id
end
# Make a request to the Microsoft Graph API, for instance https://graph.microsoft.com/v1.0/users
def request(url)
return false unless (token = bearer_token)
response = HTTParty.get(
url,
headers: {
Authorization: "Bearer #{token}"
}
)
return false unless response.code == 200
return JSON.parse(response.body)
end
private
# A post to the Microsoft Graph to get a bearer token for the specified tenant. In this example
# our Rails application has already been given permission to request these tokens by the admin of
# the specified tenant_id.
#
# See here for more information https://developer.microsoft.com/en-us/graph/docs/concepts/auth_v2_service
#
# This request also makes use of the multipart/form-data post body.
def bearer_token
response = HTTParty.post(
"#{MS_BASE_URL}/#{@tenant_id}/#{TOKEN_REQUEST_PATH}",
multipart: true,
body: {
client_id: Rails.application.credentials[Rails.env.to_sym][:microsoft_client_id],
client_secret: Rails.application.credentials[Rails.env.to_sym][:microsoft_client_secret],
scope: 'https://graph.microsoft.com/.default',
grant_type: 'client_credentials'
}
)
return false unless response.code == 200
JSON.parse(response.body)['access_token']
end
end
httparty-0.18.1/examples/multipart.rb 0000664 0000000 0000000 00000000656 13670224415 0017657 0 ustar 00root root 0000000 0000000 # If you are uploading file in params, multipart will used as content-type automatically
HTTParty.post(
'http://localhost:3000/user',
body: {
name: 'Foo Bar',
email: 'example@email.com',
avatar: File.open('/full/path/to/avatar.jpg')
}
)
# However, you can force it yourself
HTTParty.post(
'http://localhost:3000/user',
multipart: true,
body: {
name: 'Foo Bar',
email: 'example@email.com'
}
)
httparty-0.18.1/examples/nokogiri_html_parser.rb 0000664 0000000 0000000 00000000536 13670224415 0022054 0 ustar 00root root 0000000 0000000 require 'rubygems'
require 'nokogiri'
dir = File.expand_path(File.join(File.dirname(__FILE__), '..', 'lib'))
require File.join(dir, 'httparty')
require 'pp'
class HtmlParserIncluded < HTTParty::Parser
def html
Nokogiri::HTML(body)
end
end
class Page
include HTTParty
parser HtmlParserIncluded
end
pp Page.get('http://www.google.com')
httparty-0.18.1/examples/peer_cert.rb 0000664 0000000 0000000 00000000443 13670224415 0017600 0 ustar 00root root 0000000 0000000 dir = File.expand_path(File.join(File.dirname(__FILE__), '..', 'lib'))
require File.join(dir, 'httparty')
peer_cert = nil
HTTParty.get("https://www.example.com") do |fragment|
peer_cert ||= fragment.connection.peer_cert
end
puts "The server's certificate expires #{peer_cert.not_after}"
httparty-0.18.1/examples/rescue_json.rb 0000664 0000000 0000000 00000001206 13670224415 0020145 0 ustar 00root root 0000000 0000000 dir = File.expand_path(File.join(File.dirname(__FILE__), '..', 'lib'))
require File.join(dir, 'httparty')
# Take note of the "; 1" at the end of the following line. It's required only if
# running this in IRB, because IRB will try to inspect the variable named
# "request", triggering the exception.
request = HTTParty.get 'https://rubygems.org/api/v1/versions/doesnotexist.json' ; 1
# Check an exception due to parsing the response
# because HTTParty evaluate the response lazily
begin
request.inspect
# This would also suffice by forcing the request to be parsed:
# request.parsed_response
rescue => e
puts "Rescued #{e.inspect}"
end
httparty-0.18.1/examples/rubyurl.rb 0000664 0000000 0000000 00000000531 13670224415 0017332 0 ustar 00root root 0000000 0000000 dir = File.expand_path(File.join(File.dirname(__FILE__), '..', 'lib'))
require File.join(dir, 'httparty')
require 'pp'
class Rubyurl
include HTTParty
base_uri 'rubyurl.com'
def self.shorten(website_url)
post('/api/links.json', query: { link: { website_url: website_url } })
end
end
pp Rubyurl.shorten('http://istwitterdown.com/')
httparty-0.18.1/examples/stackexchange.rb 0000664 0000000 0000000 00000001025 13670224415 0020435 0 ustar 00root root 0000000 0000000 dir = File.expand_path(File.join(File.dirname(__FILE__), '..', 'lib'))
require File.join(dir, 'httparty')
require 'pp'
class StackExchange
include HTTParty
base_uri 'api.stackexchange.com'
def initialize(service, page)
@options = { query: { site: service, page: page } }
end
def questions
self.class.get("/2.2/questions", @options)
end
def users
self.class.get("/2.2/users", @options)
end
end
stack_exchange = StackExchange.new("stackoverflow", 1)
pp stack_exchange.questions
pp stack_exchange.users
httparty-0.18.1/examples/stream_download.rb 0000664 0000000 0000000 00000001363 13670224415 0021014 0 ustar 00root root 0000000 0000000 dir = File.expand_path(File.join(File.dirname(__FILE__), '..', 'lib'))
require File.join(dir, 'httparty')
require 'pp'
# download file linux-4.6.4.tar.xz without using the memory
response = nil
filename = "linux-4.6.4.tar.xz"
url = "https://cdn.kernel.org/pub/linux/kernel/v4.x/#{filename}"
File.open(filename, "w") do |file|
response = HTTParty.get(url, stream_body: true) do |fragment|
if [301, 302].include?(fragment.code)
print "skip writing for redirect"
elsif fragment.code == 200
print "."
file.write(fragment)
else
raise StandardError, "Non-success status code while streaming #{fragment.code}"
end
end
end
puts
pp "Success: #{response.success?}"
pp File.stat(filename).inspect
File.unlink(filename)
httparty-0.18.1/examples/tripit_sign_in.rb 0000664 0000000 0000000 00000002143 13670224415 0020650 0 ustar 00root root 0000000 0000000 dir = File.expand_path(File.join(File.dirname(__FILE__), '..', 'lib'))
require File.join(dir, 'httparty')
class TripIt
include HTTParty
base_uri 'https://www.tripit.com'
debug_output
def initialize(email, password)
@email = email
get_response = self.class.get('/account/login')
get_response_cookie = parse_cookie(get_response.headers['Set-Cookie'])
post_response = self.class.post(
'/account/login',
body: {
login_email_address: email,
login_password: password
},
headers: {'Cookie' => get_response_cookie.to_cookie_string }
)
@cookie = parse_cookie(post_response.headers['Set-Cookie'])
end
def account_settings
self.class.get('/account/edit', headers: { 'Cookie' => @cookie.to_cookie_string })
end
def logged_in?
account_settings.include? "You're logged in as #{@email}"
end
private
def parse_cookie(resp)
cookie_hash = CookieHash.new
resp.get_fields('Set-Cookie').each { |c| cookie_hash.add_cookies(c) }
cookie_hash
end
end
tripit = TripIt.new('email', 'password')
puts "Logged in: #{tripit.logged_in?}"
httparty-0.18.1/examples/twitter.rb 0000664 0000000 0000000 00000001720 13670224415 0017331 0 ustar 00root root 0000000 0000000 dir = File.expand_path(File.join(File.dirname(__FILE__), '..', 'lib'))
require File.join(dir, 'httparty')
require 'pp'
config = YAML.load(File.read(File.join(ENV['HOME'], '.twitter')))
class Twitter
include HTTParty
base_uri 'twitter.com'
def initialize(u, p)
@auth = {username: u, password: p}
end
# which can be :friends, :user or :public
# options[:query] can be things like since, since_id, count, etc.
def timeline(which = :friends, options = {})
options.merge!({ basic_auth: @auth })
self.class.get("/statuses/#{which}_timeline.json", options)
end
def post(text)
options = { query: { status: text }, basic_auth: @auth }
self.class.post('/statuses/update.json', options)
end
end
twitter = Twitter.new(config['email'], config['password'])
pp twitter.timeline
# pp twitter.timeline(:friends, query: {since_id: 868482746})
# pp twitter.timeline(:friends, query: 'since_id=868482746')
# pp twitter.post('this is a test of 0.2.0')
httparty-0.18.1/examples/whoismyrep.rb 0000664 0000000 0000000 00000000471 13670224415 0020037 0 ustar 00root root 0000000 0000000 dir = File.expand_path(File.join(File.dirname(__FILE__), '..', 'lib'))
require File.join(dir, 'httparty')
require 'pp'
class Rep
include HTTParty
end
pp Rep.get('http://whoismyrepresentative.com/getall_mems.php?zip=46544')
pp Rep.get('http://whoismyrepresentative.com/getall_mems.php', query: { zip: 46544 })
httparty-0.18.1/features/ 0000775 0000000 0000000 00000000000 13670224415 0015302 5 ustar 00root root 0000000 0000000 httparty-0.18.1/features/basic_authentication.feature 0000664 0000000 0000000 00000001675 13670224415 0023050 0 ustar 00root root 0000000 0000000 Feature: Basic Authentication
As a developer
I want to be able to use a service that requires Basic Authentication
Because that is not an uncommon requirement
Scenario: Passing no credentials to a page requiring Basic Authentication
Given a restricted page at '/basic_auth.html'
When I call HTTParty#get with '/basic_auth.html'
Then it should return a response with a 401 response code
Scenario: Passing proper credentials to a page requiring Basic Authentication
Given a remote service that returns 'Authenticated Page'
And that service is accessed at the path '/basic_auth.html'
And that service is protected by Basic Authentication
And that service requires the username 'jcash' with the password 'maninblack'
When I call HTTParty#get with '/basic_auth.html' and a basic_auth hash:
| username | password |
| jcash | maninblack |
Then the return value should match 'Authenticated Page'
httparty-0.18.1/features/command_line.feature 0000664 0000000 0000000 00000010261 13670224415 0021304 0 ustar 00root root 0000000 0000000 @command_line
Feature: Command Line
As a developer
I want to be able to harness the power of HTTParty from the command line
Because that would make quick testing and debugging easy
Scenario: Show help information
When I run `httparty --help`
Then the output should contain "-f, --format [FORMAT]"
Scenario: Show current version
When I run `httparty --version`
Then the output should contain "Version:"
And the output should not contain "You need to provide a URL"
Scenario: Make a get request
Given a remote deflate service on port '4001'
And the response from the service has a body of 'GET request'
And that service is accessed at the path '/fun'
When I run `httparty http://0.0.0.0:4001/fun`
Then the output should contain "GET request"
Scenario: Make a post request
Given a remote deflate service on port '4002'
And the response from the service has a body of 'POST request'
And that service is accessed at the path '/fun'
When I run `httparty http://0.0.0.0:4002/fun --action post --data "a=1&b=2"`
Then the output should contain "POST request"
Scenario: Make a put request
Given a remote deflate service on port '4003'
And the response from the service has a body of 'PUT request'
And that service is accessed at the path '/fun'
When I run `httparty http://0.0.0.0:4003/fun --action put --data "a=1&b=2"`
Then the output should contain "PUT request"
Scenario: Make a delete request
Given a remote deflate service on port '4004'
And the response from the service has a body of 'DELETE request'
And that service is accessed at the path '/fun'
When I run `httparty http://0.0.0.0:4004/fun --action delete`
Then the output should contain "DELETE request"
Scenario: Set a verbose mode
Given a remote deflate service on port '4005'
And the response from the service has a body of 'Some request'
And that service is accessed at the path '/fun'
When I run `httparty http://0.0.0.0:4005/fun --verbose`
Then the output should contain "content-length"
Scenario: Use service with basic authentication
Given a remote deflate service on port '4006'
And the response from the service has a body of 'Successfull authentication'
And that service is accessed at the path '/fun'
And that service is protected by Basic Authentication
And that service requires the username 'user' with the password 'pass'
When I run `httparty http://0.0.0.0:4006/fun --user 'user:pass'`
Then the output should contain "Successfull authentication"
Scenario: Get response in plain format
Given a remote deflate service on port '4007'
And the response from the service has a body of 'Some request'
And that service is accessed at the path '/fun'
When I run `httparty http://0.0.0.0:4007/fun --format plain`
Then the output should contain "Some request"
Scenario: Get response in json format
Given a remote deflate service on port '4008'
Given a remote service that returns '{ "jennings": "waylon", "cash": "johnny" }'
And that service is accessed at the path '/service.json'
And the response from the service has a Content-Type of 'application/json'
When I run `httparty http://0.0.0.0:4008/service.json --format json`
Then the output should contain '"jennings": "waylon"'
Scenario: Get response in xml format
Given a remote deflate service on port '4009'
Given a remote service that returns 'waylon jennings'
And that service is accessed at the path '/service.xml'
And the response from the service has a Content-Type of 'text/xml'
When I run `httparty http://0.0.0.0:4009/service.xml --format xml`
Then the output should contain ""
Scenario: Get response in csv format
Given a remote deflate service on port '4010'
Given a remote service that returns:
"""
"Last Name","Name"
"jennings","waylon"
"cash","johnny"
"""
And that service is accessed at the path '/service.csv'
And the response from the service has a Content-Type of 'application/csv'
When I run `httparty http://0.0.0.0:4010/service.csv --format csv`
Then the output should contain '["Last Name", "Name"]'
httparty-0.18.1/features/deals_with_http_error_codes.feature 0000664 0000000 0000000 00000002240 13670224415 0024425 0 ustar 00root root 0000000 0000000 Feature: Deals with HTTP error codes
As a developer
I want to be informed of non-successful responses
Because sometimes thing explode
And I should probably know what happened
Scenario: A response of '404 - Not Found'
Given a remote service that returns a 404 status code
And that service is accessed at the path '/404_service.html'
When I call HTTParty#get with '/404_service.html'
Then it should return a response with a 404 response code
Scenario: A response of '500 - Internal Server Error'
Given a remote service that returns a 500 status code
And that service is accessed at the path '/500_service.html'
When I call HTTParty#get with '/500_service.html'
Then it should return a response with a 500 response code
Scenario: A non-successful response where I need the body
Given a remote service that returns a 400 status code
And the response from the service has a body of 'Bad response'
And that service is accessed at the path '/400_service.html'
When I call HTTParty#get with '/400_service.html'
Then it should return a response with a 400 response code
And the return value should match 'Bad response'
httparty-0.18.1/features/digest_authentication.feature 0000664 0000000 0000000 00000003114 13670224415 0023234 0 ustar 00root root 0000000 0000000 Feature: Digest Authentication
As a developer
I want to be able to use a service that requires Digest Authentication
Because that is not an uncommon requirement
Scenario: Passing no credentials to a page requiring Digest Authentication
Given a restricted page at '/digest_auth.html'
When I call HTTParty#get with '/digest_auth.html'
Then it should return a response with a 401 response code
Scenario: Passing proper credentials to a page requiring Digest Authentication
Given a remote service that returns 'Digest Authenticated Page'
And that service is accessed at the path '/digest_auth.html'
And that service is protected by Digest Authentication
And that service requires the username 'jcash' with the password 'maninblack'
When I call HTTParty#get with '/digest_auth.html' and a digest_auth hash:
| username | password |
| jcash | maninblack |
Then the return value should match 'Digest Authenticated Page'
Scenario: Passing proper credentials to a page requiring Digest Authentication using md5-sess algorithm
Given a remote service that returns 'Digest Authenticated Page Using MD5-sess'
And that service is accessed at the path '/digest_auth.html'
And that service is protected by MD5-sess Digest Authentication
And that service requires the username 'jcash' with the password 'maninblack'
When I call HTTParty#get with '/digest_auth.html' and a digest_auth hash:
| username | password |
| jcash | maninblack |
Then the return value should match 'Digest Authenticated Page Using MD5-sess'
httparty-0.18.1/features/handles_compressed_responses.feature 0000664 0000000 0000000 00000003606 13670224415 0024627 0 ustar 00root root 0000000 0000000 Feature: Handles Compressed Responses
In order to save bandwidth
As a developer
I want to leverage Net::Http's built in transparent support for gzip and deflate content encoding
Scenario: Supports deflate encoding
Given a remote deflate service
And the response from the service has a body of '
Some HTML
'
And that service is accessed at the path '/deflate_service.html'
When I call HTTParty#get with '/deflate_service.html'
Then the return value should match '
Some HTML
'
And it should return a response without a content-encoding
Scenario: Supports gzip encoding
Given a remote gzip service
And the response from the service has a body of '
Some HTML
'
And that service is accessed at the path '/gzip_service.html'
When I call HTTParty#get with '/gzip_service.html'
Then the return value should match '
Some HTML
'
And it should return a response without a content-encoding
Scenario: Supports gzip encoding with explicit header set
Given a remote gzip service
And the response from the service has a body of '
Some HTML
'
And that service is accessed at the path '/gzip_service.html'
When I set my HTTParty header 'User-Agent' to value 'Party'
And I call HTTParty#get with '/gzip_service.html'
Then the return value should match '
Some HTML
'
And it should return a response without a content-encoding
Scenario: Supports deflate encoding with explicit header set
Given a remote deflate service
And the response from the service has a body of '
Some HTML
'
And that service is accessed at the path '/deflate_service.html'
When I set my HTTParty header 'User-Agent' to value 'Party'
And I call HTTParty#get with '/deflate_service.html'
Then the return value should match '
Some HTML
'
And it should return a response without a content-encoding
httparty-0.18.1/features/handles_multiple_formats.feature 0000664 0000000 0000000 00000004513 13670224415 0023746 0 ustar 00root root 0000000 0000000 Feature: Handles Multiple Formats
As a developer
I want to be able to consume remote services of many different formats
And I want those formats to be automatically detected and handled
Because web services take many forms
And I don't want to have to do any extra work
Scenario: An HTML service
Given a remote service that returns '
Some HTML
'
And that service is accessed at the path '/html_service.html'
And the response from the service has a Content-Type of 'text/html'
When I call HTTParty#get with '/html_service.html'
Then it should return a String
And the return value should match '
Some HTML
'
Scenario: A CSV service
Given a remote service that returns:
"""
"Last Name","Name"
"jennings","waylon"
"cash","johnny"
"""
And that service is accessed at the path '/service.csv'
And the response from the service has a Content-Type of 'application/csv'
When I call HTTParty#get with '/service.csv'
Then it should return an Array equaling:
| Last Name | Name |
| jennings | waylon |
| cash | johnny |
Scenario: A JSON service
Given a remote service that returns '{ "jennings": "waylon", "cash": "johnny" }'
And that service is accessed at the path '/service.json'
And the response from the service has a Content-Type of 'application/json'
When I call HTTParty#get with '/service.json'
Then it should return a Hash equaling:
| key | value |
| jennings | waylon |
| cash | johnny |
Scenario: An XML Service
Given a remote service that returns 'waylon jennings'
And that service is accessed at the path '/service.xml'
And the response from the service has a Content-Type of 'text/xml'
When I call HTTParty#get with '/service.xml'
Then it should return a Hash equaling:
| key | value |
| singer | waylon jennings |
Scenario: A Javascript remote file
Given a remote service that returns '$(function() { alert("hi"); });'
And that service is accessed at the path '/service.js'
And the response from the service has a Content-Type of 'application/javascript'
When I call HTTParty#get with '/service.js'
Then it should return a String
And the return value should match '$(function() { alert("hi"); });'
httparty-0.18.1/features/steps/ 0000775 0000000 0000000 00000000000 13670224415 0016440 5 ustar 00root root 0000000 0000000 httparty-0.18.1/features/steps/env.rb 0000664 0000000 0000000 00000000752 13670224415 0017561 0 ustar 00root root 0000000 0000000 require 'mongrel'
require './lib/httparty'
require 'rspec/expectations'
require 'aruba/cucumber'
def run_server(port)
@host_and_port = "0.0.0.0:#{port}"
@server = Mongrel::HttpServer.new("0.0.0.0", port)
@server.run
@request_options = {}
end
def new_port
server = TCPServer.new('0.0.0.0', nil)
port = server.addr[1]
ensure
server.close
end
Before('~@command_line') do
port = ENV["HTTPARTY_PORT"] || new_port
run_server(port)
end
After do
@server.stop if @server
end
httparty-0.18.1/features/steps/httparty_response_steps.rb 0000664 0000000 0000000 00000003522 13670224415 0024002 0 ustar 00root root 0000000 0000000 # Not needed anymore in ruby 2.0, but needed to resolve constants
# in nested namespaces. This is taken from rails :)
def constantize(camel_cased_word)
names = camel_cased_word.split('::')
names.shift if names.empty? || names.first.empty?
constant = Object
names.each do |name|
constant = constant.const_defined?(name) ? constant.const_get(name) : constant.const_missing(name)
end
constant
end
Then /it should return an? ([\w\:]+)$/ do |class_string|
expect(@response_from_httparty.parsed_response).to be_a(Object.const_get(class_string))
end
Then /the return value should match '(.*)'/ do |expected_text|
expect(@response_from_httparty.parsed_response).to eq(expected_text)
end
Then /it should return a Hash equaling:/ do |hash_table|
expect(@response_from_httparty.parsed_response).to be_a(Hash)
expect(@response_from_httparty.keys.length).to eq(hash_table.rows.length)
hash_table.hashes.each do |pair|
key, value = pair["key"], pair["value"]
expect(@response_from_httparty.keys).to include(key)
expect(@response_from_httparty[key]).to eq(value)
end
end
Then /it should return an Array equaling:/ do |array|
expect(@response_from_httparty.parsed_response).to be_a(Array)
expect(@response_from_httparty.parsed_response).to eq(array.raw)
end
Then /it should return a response with a (\d+) response code/ do |code|
expect(@response_from_httparty.code).to eq(code.to_i)
end
Then /it should return a response without a content\-encoding$/ do
expect(@response_from_httparty.headers['content-encoding']).to be_nil
end
Then /it should raise (?:an|a) ([\w:]+) exception/ do |exception|
expect(@exception_from_httparty).to_not be_nil
expect(@exception_from_httparty).to be_a constantize(exception)
end
Then /it should not raise (?:an|a) ([\w:]+) exception/ do |exception|
expect(@exception_from_httparty).to be_nil
end
httparty-0.18.1/features/steps/httparty_steps.rb 0000664 0000000 0000000 00000003045 13670224415 0022064 0 ustar 00root root 0000000 0000000 When /^I set my HTTParty timeout option to (\d+)$/ do |timeout|
@request_options[:timeout] = timeout.to_i
end
When /^I set my HTTParty open_timeout option to (\d+)$/ do |timeout|
@request_options[:open_timeout] = timeout.to_i
end
When /^I set my HTTParty read_timeout option to (\d+)$/ do |timeout|
@request_options[:read_timeout] = timeout.to_i
end
When /^I set my HTTParty header '(.*)' to value '(.*)'$/ do |name, value|
@request_options[:headers] ||= {}
@request_options[:headers][name] = value
end
When /I call HTTParty#get with '(.*)'$/ do |url|
begin
@response_from_httparty = HTTParty.get("http://#{@host_and_port}#{url}", @request_options)
rescue HTTParty::RedirectionTooDeep, Timeout::Error => e
@exception_from_httparty = e
end
end
When /^I call HTTParty#head with '(.*)'$/ do |url|
begin
@response_from_httparty = HTTParty.head("http://#{@host_and_port}#{url}", @request_options)
rescue HTTParty::RedirectionTooDeep, Timeout::Error => e
@exception_from_httparty = e
end
end
When /I call HTTParty#get with '(.*)' and a basic_auth hash:/ do |url, auth_table|
h = auth_table.hashes.first
@response_from_httparty = HTTParty.get(
"http://#{@host_and_port}#{url}",
basic_auth: { username: h["username"], password: h["password"] }
)
end
When /I call HTTParty#get with '(.*)' and a digest_auth hash:/ do |url, auth_table|
h = auth_table.hashes.first
@response_from_httparty = HTTParty.get(
"http://#{@host_and_port}#{url}",
digest_auth: { username: h["username"], password: h["password"] }
)
end
httparty-0.18.1/features/steps/mongrel_helper.rb 0000664 0000000 0000000 00000007506 13670224415 0021777 0 ustar 00root root 0000000 0000000 require 'base64'
class BasicMongrelHandler < Mongrel::HttpHandler
attr_accessor :content_type, :custom_headers, :response_body, :response_code, :preprocessor, :username, :password
def initialize
@content_type = "text/html"
@response_body = ""
@response_code = 200
@custom_headers = {}
end
def process(request, response)
instance_eval(&preprocessor) if preprocessor
reply_with(response, response_code, response_body)
end
def reply_with(response, code, response_body)
response.start(code) do |head, body|
head["Content-Type"] = content_type
custom_headers.each { |k, v| head[k] = v }
body.write(response_body)
end
end
end
class DeflateHandler < BasicMongrelHandler
def process(request, response)
accept_encoding = request.params["HTTP_ACCEPT_ENCODING"]
if accept_encoding.nil? || !accept_encoding.include?('deflate')
reply_with(response, 406, 'No deflate accept encoding found in request')
else
response.start do |head, body|
head['Content-Encoding'] = 'deflate'
body.write Zlib::Deflate.deflate(response_body)
end
end
end
end
class GzipHandler < BasicMongrelHandler
def process(request, response)
accept_encoding = request.params["HTTP_ACCEPT_ENCODING"]
if accept_encoding.nil? || !accept_encoding.include?('gzip')
reply_with(response, 406, 'No gzip accept encoding found in request')
else
response.start do |head, body|
head['Content-Encoding'] = 'gzip'
body.write gzip(response_body)
end
end
end
protected
def gzip(string)
sio = StringIO.new('', 'r+')
gz = Zlib::GzipWriter.new sio
gz.write string
gz.finish
sio.rewind
sio.read
end
end
module BasicAuthentication
def self.extended(base)
base.custom_headers["WWW-Authenticate"] = 'Basic Realm="Super Secret Page"'
end
def process(request, response)
if authorized?(request)
super
else
reply_with(response, 401, "Incorrect. You have 20 seconds to comply.")
end
end
def authorized?(request)
request.params["HTTP_AUTHORIZATION"] == "Basic " + Base64.encode64("#{@username}:#{@password}").strip
end
end
module DigestAuthentication
def self.extended(base)
base.custom_headers["WWW-Authenticate"] = 'Digest realm="testrealm@host.com",qop="auth,auth-int",nonce="nonce",opaque="opaque"'
end
def process(request, response)
if authorized?(request)
super
else
reply_with(response, 401, "Incorrect. You have 20 seconds to comply.")
end
end
def authorized?(request)
request.params["HTTP_AUTHORIZATION"] =~ /Digest.*uri=/
end
end
module DigestAuthenticationUsingMD5Sess
NONCE = 'nonce'
REALM = 'testrealm@host.com'
QOP = 'auth,auth-int'
def self.extended(base)
base.custom_headers["WWW-Authenticate"] = %(Digest realm="#{REALM}",qop="#{QOP}",algorithm="MD5-sess",nonce="#{NONCE}",opaque="opaque"')
end
def process(request, response)
if authorized?(request)
super
else
reply_with(response, 401, "Incorrect. You have 20 seconds to comply.")
end
end
def md5(str)
Digest::MD5.hexdigest(str)
end
def authorized?(request)
auth = request.params["HTTP_AUTHORIZATION"]
params = {}
auth.to_s.gsub(/(\w+)="(.*?)"/) { params[$1] = $2 }.gsub(/(\w+)=([^,]*)/) { params[$1] = $2 }
a1a = [@username,REALM,@password].join(':')
a1 = [md5(a1a),NONCE,params['cnonce'] ].join(':')
a2 = [ request.params["REQUEST_METHOD"], request.params["REQUEST_URI"] ] .join(':')
expected_response = md5( [md5(a1), NONCE, params['nc'], params['cnonce'], QOP, md5(a2)].join(':') )
expected_response == params['response']
end
end
def new_mongrel_redirector(target_url, relative_path = false)
target_url = "http://#{@host_and_port}#{target_url}" unless relative_path
Mongrel::RedirectHandler.new(target_url)
end
httparty-0.18.1/features/steps/remote_service_steps.rb 0000664 0000000 0000000 00000005350 13670224415 0023221 0 ustar 00root root 0000000 0000000 Given /a remote service that returns '(.*)'/ do |response_body|
@handler = BasicMongrelHandler.new
step "the response from the service has a body of '#{response_body}'"
end
Given /^a remote service that returns:$/ do |response_body|
@handler = BasicMongrelHandler.new
@handler.response_body = response_body
end
Given /a remote service that returns a (\d+) status code/ do |code|
@handler = BasicMongrelHandler.new
@handler.response_code = code
end
Given /that service is accessed at the path '(.*)'/ do |path|
@server.register(path, @handler)
end
Given /^that service takes (\d+) (.*) to generate a response$/ do |time, unit|
time = time.to_i
time *= 60 if unit =~ /minute/
@server_response_time = time
@handler.preprocessor = proc { sleep time }
end
Given /^a remote deflate service$/ do
@handler = DeflateHandler.new
end
Given /^a remote deflate service on port '(\d+)'/ do |port|
run_server(port)
@handler = DeflateHandler.new
end
Given /^a remote gzip service$/ do
@handler = GzipHandler.new
end
Given /the response from the service has a Content-Type of '(.*)'/ do |content_type|
@handler.content_type = content_type
end
Given /the response from the service has a body of '(.*)'/ do |response_body|
@handler.response_body = response_body
end
Given /the url '(.*)' redirects to '(.*)'/ do |redirection_url, target_url|
@server.register redirection_url, new_mongrel_redirector(target_url)
end
Given /that service is protected by Basic Authentication/ do
@handler.extend BasicAuthentication
end
Given /that service is protected by Digest Authentication/ do
@handler.extend DigestAuthentication
end
Given /that service is protected by MD5-sess Digest Authentication/ do
@handler.extend DigestAuthenticationUsingMD5Sess
end
Given /that service requires the username '(.*)' with the password '(.*)'/ do |username, password|
@handler.username = username
@handler.password = password
end
# customize aruba cucumber step
Then /^the output should contain '(.*)'$/ do |expected|
expect(all_commands.map(&:output).join("\n")).to match_output_string(expected)
end
Given /a restricted page at '(.*)'/ do |url|
steps "
Given a remote service that returns 'A response I will never see'
And that service is accessed at the path '#{url}'
And that service is protected by Basic Authentication
And that service requires the username 'something' with the password 'secret'
"
end
# This joins the server thread, and halts cucumber, so you can actually hit the
# server with a browser. Runs until you kill it with Ctrl-c
Given /I want to hit this in a browser/ do
@server.acceptor.join
end
Then /I wait for the server to recover/ do
timeout = @request_options[:timeout] || 0
sleep @server_response_time - timeout
end
httparty-0.18.1/features/supports_read_timeout_option.feature 0000664 0000000 0000000 00000001200 13670224415 0024700 0 ustar 00root root 0000000 0000000 Feature: Supports the read timeout option
In order to handle inappropriately slow response times
As a developer
I want my request to raise an exception after my specified read_timeout as elapsed
Scenario: A long running response
Given a remote service that returns '
Some HTML
'
And that service is accessed at the path '/long_running_service.html'
And that service takes 2 seconds to generate a response
When I set my HTTParty read_timeout option to 1
And I call HTTParty#get with '/long_running_service.html'
Then it should raise a Timeout::Error exception
And I wait for the server to recover
httparty-0.18.1/features/supports_redirection.feature 0000664 0000000 0000000 00000001654 13670224415 0023153 0 ustar 00root root 0000000 0000000 Feature: Supports Redirection
As a developer
I want to work with services that may redirect me
And I want it to follow a reasonable number of redirects
Because sometimes web services do that
Scenario: A service that redirects once
Given a remote service that returns 'Service Response'
And that service is accessed at the path '/landing_service.html'
And the url '/redirector.html' redirects to '/landing_service.html'
When I call HTTParty#get with '/redirector.html'
Then the return value should match 'Service Response'
# TODO: Look in to why this actually fails...
Scenario: A service that redirects to a relative URL
Scenario: A service that redirects infinitely
Given the url '/first.html' redirects to '/second.html'
And the url '/second.html' redirects to '/first.html'
When I call HTTParty#get with '/first.html'
Then it should raise an HTTParty::RedirectionTooDeep exception
httparty-0.18.1/features/supports_timeout_option.feature 0000664 0000000 0000000 00000001161 13670224415 0023713 0 ustar 00root root 0000000 0000000 Feature: Supports the timeout option
In order to handle inappropriately slow response times
As a developer
I want my request to raise an exception after my specified timeout as elapsed
Scenario: A long running response
Given a remote service that returns '
Some HTML
'
And that service is accessed at the path '/long_running_service.html'
And that service takes 2 seconds to generate a response
When I set my HTTParty timeout option to 1
And I call HTTParty#get with '/long_running_service.html'
Then it should raise a Timeout::Error exception
And I wait for the server to recover
httparty-0.18.1/httparty.gemspec 0000664 0000000 0000000 00000002156 13670224415 0016714 0 ustar 00root root 0000000 0000000 # -*- encoding: utf-8 -*-
$LOAD_PATH.push File.expand_path("../lib", __FILE__)
require "httparty/version"
Gem::Specification.new do |s|
s.name = "httparty"
s.version = HTTParty::VERSION
s.platform = Gem::Platform::RUBY
s.licenses = ['MIT']
s.authors = ["John Nunemaker", "Sandro Turriate"]
s.email = ["nunemaker@gmail.com"]
s.homepage = "https://github.com/jnunemaker/httparty"
s.summary = 'Makes http fun! Also, makes consuming restful web services dead easy.'
s.description = 'Makes http fun! Also, makes consuming restful web services dead easy.'
s.required_ruby_version = '>= 2.0.0'
s.add_dependency 'multi_xml', ">= 0.5.2"
s.add_dependency('mime-types', "~> 3.0")
# If this line is removed, all hard partying will cease.
s.post_install_message = "When you HTTParty, you must party hard!"
all_files = `git ls-files`.split("\n")
test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
s.files = all_files - test_files
s.executables = `git ls-files -- bin/*`.split("\n").map { |f| File.basename(f) }
s.require_paths = ["lib"]
end
httparty-0.18.1/lib/ 0000775 0000000 0000000 00000000000 13670224415 0014232 5 ustar 00root root 0000000 0000000 httparty-0.18.1/lib/httparty.rb 0000664 0000000 0000000 00000052664 13670224415 0016453 0 ustar 00root root 0000000 0000000 require 'pathname'
require 'net/http'
require 'net/https'
require 'uri'
require 'zlib'
require 'multi_xml'
require 'mime/types'
require 'json'
require 'csv'
require 'httparty/module_inheritable_attributes'
require 'httparty/cookie_hash'
require 'httparty/net_digest_auth'
require 'httparty/version'
require 'httparty/connection_adapter'
require 'httparty/logger/logger'
require 'httparty/request/body'
require 'httparty/response_fragment'
require 'httparty/text_encoder'
require 'httparty/headers_processor'
# @see HTTParty::ClassMethods
module HTTParty
def self.included(base)
base.extend ClassMethods
base.send :include, ModuleInheritableAttributes
base.send(:mattr_inheritable, :default_options)
base.send(:mattr_inheritable, :default_cookies)
base.instance_variable_set("@default_options", {})
base.instance_variable_set("@default_cookies", CookieHash.new)
end
# == Common Request Options
# Request methods (get, post, patch, put, delete, head, options) all take a common set of options. These are:
#
# [:+body+:] Body of the request. If passed an object that responds to #to_hash, will try to normalize it first, by default passing it to ActiveSupport::to_params. Any other kind of object will get used as-is.
# [:+http_proxyaddr+:] Address of proxy server to use.
# [:+http_proxyport+:] Port of proxy server to use.
# [:+http_proxyuser+:] User for proxy server authentication.
# [:+http_proxypass+:] Password for proxy server authentication.
# [:+limit+:] Maximum number of redirects to follow. Takes precedences over :+no_follow+.
# [:+query+:] Query string, or an object that responds to #to_hash representing it. Normalized according to the same rules as :+body+. If you specify this on a POST, you must use an object which responds to #to_hash. See also HTTParty::ClassMethods.default_params.
# [:+timeout+:] Timeout for opening connection and reading data.
# [:+local_host+:] Local address to bind to before connecting.
# [:+local_port+:] Local port to bind to before connecting.
# [:+body_stream+:] Allow streaming to a REST server to specify a body_stream.
# [:+stream_body+:] Allow for streaming large files without loading them into memory.
# [:+multipart+:] Force content-type to be multipart
#
# There are also another set of options with names corresponding to various class methods. The methods in question are those that let you set a class-wide default, and the options override the defaults on a request-by-request basis. Those options are:
# * :+base_uri+: see HTTParty::ClassMethods.base_uri.
# * :+basic_auth+: see HTTParty::ClassMethods.basic_auth. Only one of :+basic_auth+ and :+digest_auth+ can be used at a time; if you try using both, you'll get an ArgumentError.
# * :+debug_output+: see HTTParty::ClassMethods.debug_output.
# * :+digest_auth+: see HTTParty::ClassMethods.digest_auth. Only one of :+basic_auth+ and :+digest_auth+ can be used at a time; if you try using both, you'll get an ArgumentError.
# * :+format+: see HTTParty::ClassMethods.format.
# * :+headers+: see HTTParty::ClassMethods.headers. Must be a an object which responds to #to_hash.
# * :+maintain_method_across_redirects+: see HTTParty::ClassMethods.maintain_method_across_redirects.
# * :+no_follow+: see HTTParty::ClassMethods.no_follow.
# * :+parser+: see HTTParty::ClassMethods.parser.
# * :+uri_adapter+: see HTTParty::ClassMethods.uri_adapter
# * :+connection_adapter+: see HTTParty::ClassMethods.connection_adapter.
# * :+pem+: see HTTParty::ClassMethods.pem.
# * :+query_string_normalizer+: see HTTParty::ClassMethods.query_string_normalizer
# * :+ssl_ca_file+: see HTTParty::ClassMethods.ssl_ca_file.
# * :+ssl_ca_path+: see HTTParty::ClassMethods.ssl_ca_path.
module ClassMethods
# Turns on logging
#
# class Foo
# include HTTParty
# logger Logger.new('http_logger'), :info, :apache
# end
def logger(logger, level = :info, format = :apache)
default_options[:logger] = logger
default_options[:log_level] = level
default_options[:log_format] = format
end
# Raises HTTParty::ResponseError if response's code matches this statuses
#
# class Foo
# include HTTParty
# raise_on [404, 500]
# end
def raise_on(codes = [])
default_options[:raise_on] = *codes
end
# Allows setting http proxy information to be used
#
# class Foo
# include HTTParty
# http_proxy 'http://foo.com', 80, 'user', 'pass'
# end
def http_proxy(addr = nil, port = nil, user = nil, pass = nil)
default_options[:http_proxyaddr] = addr
default_options[:http_proxyport] = port
default_options[:http_proxyuser] = user
default_options[:http_proxypass] = pass
end
# Allows setting a base uri to be used for each request.
# Will normalize uri to include http, etc.
#
# class Foo
# include HTTParty
# base_uri 'twitter.com'
# end
def base_uri(uri = nil)
return default_options[:base_uri] unless uri
default_options[:base_uri] = HTTParty.normalize_base_uri(uri)
end
# Allows setting basic authentication username and password.
#
# class Foo
# include HTTParty
# basic_auth 'username', 'password'
# end
def basic_auth(u, p)
default_options[:basic_auth] = {username: u, password: p}
end
# Allows setting digest authentication username and password.
#
# class Foo
# include HTTParty
# digest_auth 'username', 'password'
# end
def digest_auth(u, p)
default_options[:digest_auth] = {username: u, password: p}
end
# Do not send rails style query strings.
# Specifically, don't use bracket notation when sending an array
#
# For a query:
# get '/', query: {selected_ids: [1,2,3]}
#
# The default query string looks like this:
# /?selected_ids[]=1&selected_ids[]=2&selected_ids[]=3
#
# Call `disable_rails_query_string_format` to transform the query string
# into:
# /?selected_ids=1&selected_ids=2&selected_ids=3
#
# @example
# class Foo
# include HTTParty
# disable_rails_query_string_format
# end
def disable_rails_query_string_format
query_string_normalizer Request::NON_RAILS_QUERY_STRING_NORMALIZER
end
# Allows setting default parameters to be appended to each request.
# Great for api keys and such.
#
# class Foo
# include HTTParty
# default_params api_key: 'secret', another: 'foo'
# end
def default_params(h = {})
raise ArgumentError, 'Default params must be an object which responds to #to_hash' unless h.respond_to?(:to_hash)
default_options[:default_params] ||= {}
default_options[:default_params].merge!(h)
end
# Allows setting a default timeout for all HTTP calls
# Timeout is specified in seconds.
#
# class Foo
# include HTTParty
# default_timeout 10
# end
def default_timeout(value)
validate_timeout_argument(__method__, value)
default_options[:timeout] = value
end
# Allows setting a default open_timeout for all HTTP calls in seconds
#
# class Foo
# include HTTParty
# open_timeout 10
# end
def open_timeout(value)
validate_timeout_argument(__method__, value)
default_options[:open_timeout] = value
end
# Allows setting a default read_timeout for all HTTP calls in seconds
#
# class Foo
# include HTTParty
# read_timeout 10
# end
def read_timeout(value)
validate_timeout_argument(__method__, value)
default_options[:read_timeout] = value
end
# Allows setting a default write_timeout for all HTTP calls in seconds
# Supported by Ruby > 2.6.0
#
# class Foo
# include HTTParty
# write_timeout 10
# end
def write_timeout(value)
validate_timeout_argument(__method__, value)
default_options[:write_timeout] = value
end
# Set an output stream for debugging, defaults to $stderr.
# The output stream is passed on to Net::HTTP#set_debug_output.
#
# class Foo
# include HTTParty
# debug_output $stderr
# end
def debug_output(stream = $stderr)
default_options[:debug_output] = stream
end
# Allows setting HTTP headers to be used for each request.
#
# class Foo
# include HTTParty
# headers 'Accept' => 'text/html'
# end
def headers(h = nil)
if h
raise ArgumentError, 'Headers must be an object which responds to #to_hash' unless h.respond_to?(:to_hash)
default_options[:headers] ||= {}
default_options[:headers].merge!(h.to_hash)
else
default_options[:headers] || {}
end
end
def cookies(h = {})
raise ArgumentError, 'Cookies must be an object which responds to #to_hash' unless h.respond_to?(:to_hash)
default_cookies.add_cookies(h)
end
# Proceed to the location header when an HTTP response dictates a redirect.
# Redirects are always followed by default.
#
# @example
# class Foo
# include HTTParty
# base_uri 'http://google.com'
# follow_redirects true
# end
def follow_redirects(value = true)
default_options[:follow_redirects] = value
end
# Allows setting the format with which to parse.
# Must be one of the allowed formats ie: json, xml
#
# class Foo
# include HTTParty
# format :json
# end
def format(f = nil)
if f.nil?
default_options[:format]
else
parser(Parser) if parser.nil?
default_options[:format] = f
validate_format
end
end
# Declare whether or not to follow redirects. When true, an
# {HTTParty::RedirectionTooDeep} error will raise upon encountering a
# redirect. You can then gain access to the response object via
# HTTParty::RedirectionTooDeep#response.
#
# @see HTTParty::ResponseError#response
#
# @example
# class Foo
# include HTTParty
# base_uri 'http://google.com'
# no_follow true
# end
#
# begin
# Foo.get('/')
# rescue HTTParty::RedirectionTooDeep => e
# puts e.response.body
# end
def no_follow(value = false)
default_options[:no_follow] = value
end
# Declare that you wish to maintain the chosen HTTP method across redirects.
# The default behavior is to follow redirects via the GET method, except
# if you are making a HEAD request, in which case the default is to
# follow all redirects with HEAD requests.
# If you wish to maintain the original method, you can set this option to true.
#
# @example
# class Foo
# include HTTParty
# base_uri 'http://google.com'
# maintain_method_across_redirects true
# end
def maintain_method_across_redirects(value = true)
default_options[:maintain_method_across_redirects] = value
end
# Declare that you wish to resend the full HTTP request across redirects,
# even on redirects that should logically become GET requests.
# A 303 redirect in HTTP signifies that the redirected url should normally
# retrieved using a GET request, for instance, it is the output of a previous
# POST. maintain_method_across_redirects respects this behavior, but you
# can force HTTParty to resend_on_redirect even on 303 responses.
#
# @example
# class Foo
# include HTTParty
# base_uri 'http://google.com'
# resend_on_redirect
# end
def resend_on_redirect(value = true)
default_options[:resend_on_redirect] = value
end
# Allows setting a PEM file to be used
#
# class Foo
# include HTTParty
# pem File.read('/home/user/my.pem'), "optional password"
# end
def pem(pem_contents, password = nil)
default_options[:pem] = pem_contents
default_options[:pem_password] = password
end
# Allows setting a PKCS12 file to be used
#
# class Foo
# include HTTParty
# pkcs12 File.read('/home/user/my.p12'), "password"
# end
def pkcs12(p12_contents, password)
default_options[:p12] = p12_contents
default_options[:p12_password] = password
end
# Override the way query strings are normalized.
# Helpful for overriding the default rails normalization of Array queries.
#
# For a query:
# get '/', query: {selected_ids: [1,2,3]}
#
# The default query string normalizer returns:
# /?selected_ids[]=1&selected_ids[]=2&selected_ids[]=3
#
# Let's change it to this:
# /?selected_ids=1&selected_ids=2&selected_ids=3
#
# Pass a Proc to the query normalizer which accepts the yielded query.
#
# @example Modifying Array query strings
# class ServiceWrapper
# include HTTParty
#
# query_string_normalizer proc { |query|
# query.map do |key, value|
# value.map {|v| "#{key}=#{v}"}
# end.join('&')
# }
# end
#
# @param [Proc] normalizer custom query string normalizer.
# @yield [Hash, String] query string
# @yieldreturn [Array] an array that will later be joined with '&'
def query_string_normalizer(normalizer)
default_options[:query_string_normalizer] = normalizer
end
# Allows setting of SSL version to use. This only works in Ruby 1.9+.
# You can get a list of valid versions from OpenSSL::SSL::SSLContext::METHODS.
#
# class Foo
# include HTTParty
# ssl_version :SSLv3
# end
def ssl_version(version)
default_options[:ssl_version] = version
end
# Allows setting of SSL ciphers to use. This only works in Ruby 1.9+.
# You can get a list of valid specific ciphers from OpenSSL::Cipher.ciphers.
# You also can specify a cipher suite here, listed here at openssl.org:
# http://www.openssl.org/docs/apps/ciphers.html#CIPHER_SUITE_NAMES
#
# class Foo
# include HTTParty
# ciphers "RC4-SHA"
# end
def ciphers(cipher_names)
default_options[:ciphers] = cipher_names
end
# Allows setting an OpenSSL certificate authority file. The file
# should contain one or more certificates in PEM format.
#
# Setting this option enables certificate verification. All
# certificates along a chain must be available in ssl_ca_file or
# ssl_ca_path for verification to succeed.
#
#
# class Foo
# include HTTParty
# ssl_ca_file '/etc/ssl/certs/ca-certificates.crt'
# end
def ssl_ca_file(path)
default_options[:ssl_ca_file] = path
end
# Allows setting an OpenSSL certificate authority path (directory).
#
# Setting this option enables certificate verification. All
# certificates along a chain must be available in ssl_ca_file or
# ssl_ca_path for verification to succeed.
#
# class Foo
# include HTTParty
# ssl_ca_path '/etc/ssl/certs/'
# end
def ssl_ca_path(path)
default_options[:ssl_ca_path] = path
end
# Allows setting a custom parser for the response.
#
# class Foo
# include HTTParty
# parser Proc.new {|data| ...}
# end
def parser(custom_parser = nil)
if custom_parser.nil?
default_options[:parser]
else
default_options[:parser] = custom_parser
validate_format
end
end
# Allows setting a custom URI adapter.
#
# class Foo
# include HTTParty
# uri_adapter Addressable::URI
# end
def uri_adapter(uri_adapter)
raise ArgumentError, 'The URI adapter should respond to #parse' unless uri_adapter.respond_to?(:parse)
default_options[:uri_adapter] = uri_adapter
end
# Allows setting a custom connection_adapter for the http connections
#
# @example
# class Foo
# include HTTParty
# connection_adapter Proc.new {|uri, options| ... }
# end
#
# @example provide optional configuration for your connection_adapter
# class Foo
# include HTTParty
# connection_adapter Proc.new {|uri, options| ... }, {foo: :bar}
# end
#
# @see HTTParty::ConnectionAdapter
def connection_adapter(custom_adapter = nil, options = nil)
if custom_adapter.nil?
default_options[:connection_adapter]
else
default_options[:connection_adapter] = custom_adapter
default_options[:connection_adapter_options] = options
end
end
# Allows making a get request to a url.
#
# class Foo
# include HTTParty
# end
#
# # Simple get with full url
# Foo.get('http://foo.com/resource.json')
#
# # Simple get with full url and query parameters
# # ie: http://foo.com/resource.json?limit=10
# Foo.get('http://foo.com/resource.json', query: {limit: 10})
def get(path, options = {}, &block)
perform_request Net::HTTP::Get, path, options, &block
end
# Allows making a post request to a url.
#
# class Foo
# include HTTParty
# end
#
# # Simple post with full url and setting the body
# Foo.post('http://foo.com/resources', body: {bar: 'baz'})
#
# # Simple post with full url using :query option,
# # which appends the parameters to the URI.
# Foo.post('http://foo.com/resources', query: {bar: 'baz'})
def post(path, options = {}, &block)
perform_request Net::HTTP::Post, path, options, &block
end
# Perform a PATCH request to a path
def patch(path, options = {}, &block)
perform_request Net::HTTP::Patch, path, options, &block
end
# Perform a PUT request to a path
def put(path, options = {}, &block)
perform_request Net::HTTP::Put, path, options, &block
end
# Perform a DELETE request to a path
def delete(path, options = {}, &block)
perform_request Net::HTTP::Delete, path, options, &block
end
# Perform a MOVE request to a path
def move(path, options = {}, &block)
perform_request Net::HTTP::Move, path, options, &block
end
# Perform a COPY request to a path
def copy(path, options = {}, &block)
perform_request Net::HTTP::Copy, path, options, &block
end
# Perform a HEAD request to a path
def head(path, options = {}, &block)
ensure_method_maintained_across_redirects options
perform_request Net::HTTP::Head, path, options, &block
end
# Perform an OPTIONS request to a path
def options(path, options = {}, &block)
perform_request Net::HTTP::Options, path, options, &block
end
# Perform a MKCOL request to a path
def mkcol(path, options = {}, &block)
perform_request Net::HTTP::Mkcol, path, options, &block
end
def lock(path, options = {}, &block)
perform_request Net::HTTP::Lock, path, options, &block
end
def unlock(path, options = {}, &block)
perform_request Net::HTTP::Unlock, path, options, &block
end
attr_reader :default_options
private
def validate_timeout_argument(timeout_type, value)
raise ArgumentError, "#{ timeout_type } must be an integer or float" unless value && (value.is_a?(Integer) || value.is_a?(Float))
end
def ensure_method_maintained_across_redirects(options)
unless options.key?(:maintain_method_across_redirects)
options[:maintain_method_across_redirects] = true
end
end
def perform_request(http_method, path, options, &block) #:nodoc:
options = ModuleInheritableAttributes.hash_deep_dup(default_options).merge(options)
HeadersProcessor.new(headers, options).call
process_cookies(options)
Request.new(http_method, path, options).perform(&block)
end
def process_cookies(options) #:nodoc:
return unless options[:cookies] || default_cookies.any?
options[:headers] ||= headers.dup
options[:headers]["cookie"] = cookies.merge(options.delete(:cookies) || {}).to_cookie_string
end
def validate_format
if format && parser.respond_to?(:supports_format?) && !parser.supports_format?(format)
supported_format_names = parser.supported_formats.map(&:to_s).sort.join(', ')
raise UnsupportedFormat, "'#{format.inspect}' Must be one of: #{supported_format_names}"
end
end
end
def self.normalize_base_uri(url) #:nodoc:
normalized_url = url.dup
use_ssl = (normalized_url =~ /^https/) || (normalized_url =~ /:443\b/)
ends_with_slash = normalized_url =~ /\/$/
normalized_url.chop! if ends_with_slash
normalized_url.gsub!(/^https?:\/\//i, '')
"http#{'s' if use_ssl}://#{normalized_url}"
end
class Basement #:nodoc:
include HTTParty
end
def self.get(*args, &block)
Basement.get(*args, &block)
end
def self.post(*args, &block)
Basement.post(*args, &block)
end
def self.patch(*args, &block)
Basement.patch(*args, &block)
end
def self.put(*args, &block)
Basement.put(*args, &block)
end
def self.delete(*args, &block)
Basement.delete(*args, &block)
end
def self.move(*args, &block)
Basement.move(*args, &block)
end
def self.copy(*args, &block)
Basement.copy(*args, &block)
end
def self.head(*args, &block)
Basement.head(*args, &block)
end
def self.options(*args, &block)
Basement.options(*args, &block)
end
end
require 'httparty/hash_conversions'
require 'httparty/utils'
require 'httparty/exceptions'
require 'httparty/parser'
require 'httparty/request'
require 'httparty/response'
httparty-0.18.1/lib/httparty/ 0000775 0000000 0000000 00000000000 13670224415 0016111 5 ustar 00root root 0000000 0000000 httparty-0.18.1/lib/httparty/connection_adapter.rb 0000664 0000000 0000000 00000020336 13670224415 0022301 0 ustar 00root root 0000000 0000000 module HTTParty
# Default connection adapter that returns a new Net::HTTP each time
#
# == Custom Connection Factories
#
# If you like to implement your own connection adapter, subclassing
# HTTParty::ConnectionAdapter will make it easier. Just override
# the #connection method. The uri and options attributes will have
# all the info you need to construct your http connection. Whatever
# you return from your connection method needs to adhere to the
# Net::HTTP interface as this is what HTTParty expects.
#
# @example log the uri and options
# class LoggingConnectionAdapter < HTTParty::ConnectionAdapter
# def connection
# puts uri
# puts options
# Net::HTTP.new(uri)
# end
# end
#
# @example count number of http calls
# class CountingConnectionAdapter < HTTParty::ConnectionAdapter
# @@count = 0
#
# self.count
# @@count
# end
#
# def connection
# self.count += 1
# super
# end
# end
#
# === Configuration
# There is lots of configuration data available for your connection adapter
# in the #options attribute. It is up to you to interpret them within your
# connection adapter. Take a look at the implementation of
# HTTParty::ConnectionAdapter#connection for examples of how they are used.
# The keys used in options are
# * :+timeout+: timeout in seconds
# * :+open_timeout+: http connection open_timeout in seconds, overrides timeout if set
# * :+read_timeout+: http connection read_timeout in seconds, overrides timeout if set
# * :+write_timeout+: http connection write_timeout in seconds, overrides timeout if set (Ruby >= 2.6.0 required)
# * :+debug_output+: see HTTParty::ClassMethods.debug_output.
# * :+cert_store+: contains certificate data. see method 'attach_ssl_certificates'
# * :+pem+: contains pem client certificate data. see method 'attach_ssl_certificates'
# * :+p12+: contains PKCS12 client client certificate data. see method 'attach_ssl_certificates'
# * :+verify+: verify the server’s certificate against the ca certificate.
# * :+verify_peer+: set to false to turn off server verification but still send client certificate
# * :+ssl_ca_file+: see HTTParty::ClassMethods.ssl_ca_file.
# * :+ssl_ca_path+: see HTTParty::ClassMethods.ssl_ca_path.
# * :+ssl_version+: SSL versions to allow. see method 'attach_ssl_certificates'
# * :+ciphers+: The list of SSL ciphers to support
# * :+connection_adapter_options+: contains the hash you passed to HTTParty.connection_adapter when you configured your connection adapter
# * :+local_host+: The local address to bind to
# * :+local_port+: The local port to bind to
# * :+http_proxyaddr+: HTTP Proxy address
# * :+http_proxyport+: HTTP Proxy port
# * :+http_proxyuser+: HTTP Proxy user
# * :+http_proxypass+: HTTP Proxy password
#
# === Inherited methods
# * :+clean_host+: Method used to sanitize host names
class ConnectionAdapter
# Private: Regex used to strip brackets from IPv6 URIs.
StripIpv6BracketsRegex = /\A\[(.*)\]\z/
OPTION_DEFAULTS = {
verify: true,
verify_peer: true
}
# Public
def self.call(uri, options)
new(uri, options).connection
end
def self.default_cert_store
@default_cert_store ||= OpenSSL::X509::Store.new.tap do |cert_store|
cert_store.set_default_paths
end
end
attr_reader :uri, :options
def initialize(uri, options = {})
uri_adapter = options[:uri_adapter] || URI
raise ArgumentError, "uri must be a #{uri_adapter}, not a #{uri.class}" unless uri.is_a? uri_adapter
@uri = uri
@options = OPTION_DEFAULTS.merge(options)
end
def connection
host = clean_host(uri.host)
port = uri.port || (uri.scheme == 'https' ? 443 : 80)
if options.key?(:http_proxyaddr)
http = Net::HTTP.new(
host,
port,
options[:http_proxyaddr],
options[:http_proxyport],
options[:http_proxyuser],
options[:http_proxypass]
)
else
http = Net::HTTP.new(host, port)
end
http.use_ssl = ssl_implied?(uri)
attach_ssl_certificates(http, options)
if add_timeout?(options[:timeout])
http.open_timeout = options[:timeout]
http.read_timeout = options[:timeout]
from_ruby_version('2.6.0', option: :write_timeout, warn: false) do
http.write_timeout = options[:timeout]
end
end
if add_timeout?(options[:read_timeout])
http.read_timeout = options[:read_timeout]
end
if add_timeout?(options[:open_timeout])
http.open_timeout = options[:open_timeout]
end
if add_timeout?(options[:write_timeout])
from_ruby_version('2.6.0', option: :write_timeout) do
http.write_timeout = options[:write_timeout]
end
end
if add_max_retries?(options[:max_retries])
from_ruby_version('2.5.0', option: :max_retries) do
http.max_retries = options[:max_retries]
end
end
if options[:debug_output]
http.set_debug_output(options[:debug_output])
end
if options[:ciphers]
http.ciphers = options[:ciphers]
end
# Bind to a specific local address or port
#
# @see https://bugs.ruby-lang.org/issues/6617
if options[:local_host]
from_ruby_version('2.0.0', option: :local_host) do
http.local_host = options[:local_host]
end
end
if options[:local_port]
from_ruby_version('2.0.0', option: :local_port) do
http.local_port = options[:local_port]
end
end
http
end
private
def from_ruby_version(ruby_version, option: nil, warn: true)
if RUBY_VERSION >= ruby_version
yield
elsif warn
Kernel.warn("Warning: option #{ option } requires Ruby version #{ ruby_version } or later")
end
end
def add_timeout?(timeout)
timeout && (timeout.is_a?(Integer) || timeout.is_a?(Float))
end
def add_max_retries?(max_retries)
max_retries && max_retries.is_a?(Integer) && max_retries >= 0
end
def clean_host(host)
strip_ipv6_brackets(host)
end
def strip_ipv6_brackets(host)
StripIpv6BracketsRegex =~ host ? $1 : host
end
def ssl_implied?(uri)
uri.port == 443 || uri.scheme == 'https'
end
def verify_ssl_certificate?
!(options[:verify] == false || options[:verify_peer] == false)
end
def attach_ssl_certificates(http, options)
if http.use_ssl?
if options.fetch(:verify, true)
http.verify_mode = OpenSSL::SSL::VERIFY_PEER
if options[:cert_store]
http.cert_store = options[:cert_store]
else
# Use the default cert store by default, i.e. system ca certs
http.cert_store = self.class.default_cert_store
end
else
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
end
# Client certificate authentication
# Note: options[:pem] must contain the content of a PEM file having the private key appended
if options[:pem]
http.cert = OpenSSL::X509::Certificate.new(options[:pem])
http.key = OpenSSL::PKey::RSA.new(options[:pem], options[:pem_password])
http.verify_mode = verify_ssl_certificate? ? OpenSSL::SSL::VERIFY_PEER : OpenSSL::SSL::VERIFY_NONE
end
# PKCS12 client certificate authentication
if options[:p12]
p12 = OpenSSL::PKCS12.new(options[:p12], options[:p12_password])
http.cert = p12.certificate
http.key = p12.key
http.verify_mode = verify_ssl_certificate? ? OpenSSL::SSL::VERIFY_PEER : OpenSSL::SSL::VERIFY_NONE
end
# SSL certificate authority file and/or directory
if options[:ssl_ca_file]
http.ca_file = options[:ssl_ca_file]
http.verify_mode = OpenSSL::SSL::VERIFY_PEER
end
if options[:ssl_ca_path]
http.ca_path = options[:ssl_ca_path]
http.verify_mode = OpenSSL::SSL::VERIFY_PEER
end
# This is only Ruby 1.9+
if options[:ssl_version] && http.respond_to?(:ssl_version=)
http.ssl_version = options[:ssl_version]
end
end
end
end
end
httparty-0.18.1/lib/httparty/cookie_hash.rb 0000664 0000000 0000000 00000001053 13670224415 0020711 0 ustar 00root root 0000000 0000000 class HTTParty::CookieHash < Hash #:nodoc:
CLIENT_COOKIES = %w(path expires domain path secure httponly samesite)
def add_cookies(data)
case data
when Hash
merge!(data)
when String
data.split('; ').each do |cookie|
key, value = cookie.split('=', 2)
self[key.to_sym] = value if key
end
else
raise "add_cookies only takes a Hash or a String"
end
end
def to_cookie_string
select { |k, v| !CLIENT_COOKIES.include?(k.to_s.downcase) }.collect { |k, v| "#{k}=#{v}" }.join("; ")
end
end
httparty-0.18.1/lib/httparty/exceptions.rb 0000664 0000000 0000000 00000002273 13670224415 0020623 0 ustar 00root root 0000000 0000000 module HTTParty
# @abstact Exceptions raised by HTTParty inherit from Error
class Error < StandardError; end
# Exception raised when you attempt to set a non-existent format
class UnsupportedFormat < Error; end
# Exception raised when using a URI scheme other than HTTP or HTTPS
class UnsupportedURIScheme < Error; end
# @abstract Exceptions which inherit from ResponseError contain the Net::HTTP
# response object accessible via the {#response} method.
class ResponseError < Error
# Returns the response of the last request
# @return [Net::HTTPResponse] A subclass of Net::HTTPResponse, e.g.
# Net::HTTPOK
attr_reader :response
# Instantiate an instance of ResponseError with a Net::HTTPResponse object
# @param [Net::HTTPResponse]
def initialize(response)
@response = response
super(response)
end
end
# Exception that is raised when request has redirected too many times.
# Calling {#response} returns the Net:HTTP response object.
class RedirectionTooDeep < ResponseError; end
# Exception that is raised when request redirects and location header is present more than once
class DuplicateLocationHeader < ResponseError; end
end
httparty-0.18.1/lib/httparty/hash_conversions.rb 0000664 0000000 0000000 00000004145 13670224415 0022015 0 ustar 00root root 0000000 0000000 require 'erb'
module HTTParty
module HashConversions
# @return This hash as a query string
#
# @example
# { name: "Bob",
# address: {
# street: '111 Ruby Ave.',
# city: 'Ruby Central',
# phones: ['111-111-1111', '222-222-2222']
# }
# }.to_params
# #=> "name=Bob&address[city]=Ruby Central&address[phones][]=111-111-1111&address[phones][]=222-222-2222&address[street]=111 Ruby Ave."
def self.to_params(hash)
hash.to_hash.map { |k, v| normalize_param(k, v) }.join.chop
end
# @param key