Git Product home page Git Product logo

rest-client's Introduction

REST Client -- simple DSL for accessing HTTP and REST resources

Gem Downloads Build Status Code Climate Inline docs Join the chat at https://gitter.im/ruby-rest-client/community

A simple HTTP and REST client for Ruby, inspired by the Sinatra's microframework style of specifying actions: get, put, post, delete.

New mailing list

We have a new email list for announcements, hosted by Groups.io.

The old Librelist mailing list is defunct, as Librelist appears to be broken and not accepting new mail. The old archives are still up, but have been imported into the new list archives as well. http://librelist.com/browser/rest.client

Requirements

MRI Ruby 2.0 and newer are supported. Alternative interpreters compatible with 2.0+ should work as well.

Earlier Ruby versions such as 1.8.7, 1.9.2, and 1.9.3 are no longer supported. These versions no longer have any official support, and do not receive security updates.

The rest-client gem depends on these other gems for usage at runtime:

There are also several development dependencies. It's recommended to use bundler to manage these dependencies for hacking on rest-client.

Upgrading to rest-client 2.0 from 1.x

Users are encouraged to upgrade to rest-client 2.0, which cleans up a number of API warts and wrinkles, making rest-client generally more useful. Usage is largely compatible, so many applications will be able to upgrade with no changes.

Overview of significant changes:

  • requires Ruby >= 2.0
  • RestClient::Response objects are a subclass of String rather than a Frankenstein monster. And #body or #to_s return a true String object.
  • cleanup of exception classes, including new RestClient::Exceptions::Timeout
  • improvements to handling of redirects: responses and history are properly exposed
  • major changes to cookie support: cookie jars are used for browser-like behavior throughout
  • encoding: Content-Type charset response headers are used to automatically set the encoding of the response string
  • HTTP params: handling of GET/POST params is more consistent and sophisticated for deeply nested hash objects, and ParamsArray can be used to pass ordered params
  • improved proxy support with per-request proxy configuration, plus the ability to disable proxies set by environment variables
  • default request headers: rest-client sets Accept: */* and User-Agent: rest-client/...

See history.md for a more complete description of changes.

Usage: Raw URL

Basic usage:

require 'rest-client'

RestClient.get(url, headers={})

RestClient.post(url, payload, headers={})

In the high level helpers, only POST, PATCH, and PUT take a payload argument. To pass a payload with other HTTP verbs or to pass more advanced options, use RestClient::Request.execute instead.

More detailed examples:

require 'rest-client'

RestClient.get 'http://example.com/resource'

RestClient.get 'http://example.com/resource', {params: {id: 50, 'foo' => 'bar'}}

RestClient.get 'https://user:[email protected]/private/resource', {accept: :json}

RestClient.post 'http://example.com/resource', {param1: 'one', nested: {param2: 'two'}}

RestClient.post "http://example.com/resource", {'x' => 1}.to_json, {content_type: :json, accept: :json}

RestClient.delete 'http://example.com/resource'

>> response = RestClient.get 'http://example.com/resource'
=> <RestClient::Response 200 "<!doctype h...">
>> response.code
=> 200
>> response.cookies
=> {"Foo"=>"BAR", "QUUX"=>"QUUUUX"}
>> response.headers
=> {:content_type=>"text/html; charset=utf-8", :cache_control=>"private" ... }
>> response.body
=> "<!doctype html>\n<html>\n<head>\n    <title>Example Domain</title>\n\n ..."

RestClient.post( url,
  {
    :transfer => {
      :path => '/foo/bar',
      :owner => 'that_guy',
      :group => 'those_guys'
    },
     :upload => {
      :file => File.new(path, 'rb')
    }
  })

Passing advanced options

The top level helper methods like RestClient.get accept a headers hash as their last argument and don't allow passing more complex options. But these helpers are just thin wrappers around RestClient::Request.execute.

RestClient::Request.execute(method: :get, url: 'http://example.com/resource',
                            timeout: 10)

RestClient::Request.execute(method: :get, url: 'http://example.com/resource',
                            ssl_ca_file: 'myca.pem',
                            ssl_ciphers: 'AESGCM:!aNULL')

You can also use this to pass a payload for HTTP verbs like DELETE, where the RestClient.delete helper doesn't accept a payload.

RestClient::Request.execute(method: :delete, url: 'http://example.com/resource',
                            payload: 'foo', headers: {myheader: 'bar'})

Due to unfortunate choices in the original API, the params used to populate the query string are actually taken out of the headers hash. So if you want to pass both the params hash and more complex options, use the special key :params in the headers hash. This design may change in a future major release.

RestClient::Request.execute(method: :get, url: 'http://example.com/resource',
                            timeout: 10, headers: {params: {foo: 'bar'}})

 GET http://example.com/resource?foo=bar

Multipart

Yeah, that's right! This does multipart sends for you!

RestClient.post '/data', :myfile => File.new("/path/to/image.jpg", 'rb')

This does two things for you:

  • Auto-detects that you have a File value sends it as multipart
  • Auto-detects the mime of the file and sets it in the HEAD of the payload for each entry

If you are sending params that do not contain a File object but the payload needs to be multipart then:

RestClient.post '/data', {:foo => 'bar', :multipart => true}

Usage: ActiveResource-Style

resource = RestClient::Resource.new 'http://example.com/resource'
resource.get

private_resource = RestClient::Resource.new 'https://example.com/private/resource', 'user', 'pass'
private_resource.put File.read('pic.jpg'), :content_type => 'image/jpg'

See RestClient::Resource module docs for details.

Usage: Resource Nesting

site = RestClient::Resource.new('http://example.com')
site['posts/1/comments'].post 'Good article.', :content_type => 'text/plain'

See RestClient::Resource docs for details.

  • for result codes between 200 and 207, a RestClient::Response will be returned
  • for result codes 301, 302 or 307, the redirection will be followed if the request is a GET or a HEAD
  • for result code 303, the redirection will be followed and the request transformed into a GET
  • for other cases, a RestClient::ExceptionWithResponse holding the Response will be raised; a specific exception class will be thrown for known error codes
  • call .response on the exception to get the server's response
>> RestClient.get 'http://example.com/nonexistent'
Exception: RestClient::NotFound: 404 Not Found

>> begin
     RestClient.get 'http://example.com/nonexistent'
   rescue RestClient::ExceptionWithResponse => e
     e.response
   end
=> <RestClient::Response 404 "<!doctype h...">

Other exceptions

While most exceptions have been collected under RestClient::RequestFailed aka RestClient::ExceptionWithResponse, there are a few quirky exceptions that have been kept for backwards compatibility.

RestClient will propagate up exceptions like socket errors without modification:

>> RestClient.get 'http://localhost:12345'
Exception: Errno::ECONNREFUSED: Connection refused - connect(2) for "localhost" port 12345

RestClient handles a few specific error cases separately in order to give better error messages. These will hopefully be cleaned up in a future major release.

RestClient::ServerBrokeConnection is translated from EOFError to give a better error message.

RestClient::SSLCertificateNotVerified is raised when HTTPS validation fails. Other OpenSSL::SSL::SSLError errors are raised as is.

Redirection

By default, rest-client will follow HTTP 30x redirection requests.

New in 2.0: RestClient::Response exposes a #history method that returns a list of each response received in a redirection chain.

>> r = RestClient.get('http://httpbin.org/redirect/2')
=> <RestClient::Response 200 "{\n  \"args\":...">

# see each response in the redirect chain
>> r.history
=> [<RestClient::Response 302 "<!DOCTYPE H...">, <RestClient::Response 302 "">]

# see each requested URL
>> r.request.url
=> "http://httpbin.org/get"
>> r.history.map {|x| x.request.url}
=> ["http://httpbin.org/redirect/2", "http://httpbin.org/relative-redirect/1"]

Manually following redirection

To disable automatic redirection, set :max_redirects => 0.

New in 2.0: Prior versions of rest-client would raise RestClient::MaxRedirectsReached, with no easy way to access the server's response. In 2.0, rest-client raises the normal RestClient::ExceptionWithResponse as it would with any other non-HTTP-20x response.

>> RestClient::Request.execute(method: :get, url: 'http://httpbin.org/redirect/1')
=> RestClient::Response 200 "{\n  "args":..."

>> RestClient::Request.execute(method: :get, url: 'http://httpbin.org/redirect/1', max_redirects: 0)
RestClient::Found: 302 Found

To manually follow redirection, you can call Response#follow_redirection. Or you could of course inspect the result and choose custom behavior.

>> RestClient::Request.execute(method: :get, url: 'http://httpbin.org/redirect/1', max_redirects: 0)
RestClient::Found: 302 Found
>> begin
       RestClient::Request.execute(method: :get, url: 'http://httpbin.org/redirect/1', max_redirects: 0)
   rescue RestClient::ExceptionWithResponse => err
   end
>> err
=> #<RestClient::Found: 302 Found>
>> err.response
=> RestClient::Response 302 "<!DOCTYPE H..."
>> err.response.headers[:location]
=> "/get"
>> err.response.follow_redirection
=> RestClient::Response 200 "{\n  "args":..."

Result handling

The result of a RestClient::Request is a RestClient::Response object.

New in 2.0: RestClient::Response objects are now a subclass of String. Previously, they were a real String object with response functionality mixed in, which was very confusing to work with.

Response objects have several useful methods. (See the class rdoc for more details.)

  • Response#code: The HTTP response code
  • Response#body: The response body as a string. (AKA .to_s)
  • Response#headers: A hash of HTTP response headers
  • Response#raw_headers: A hash of HTTP response headers as unprocessed arrays
  • Response#cookies: A hash of HTTP cookies set by the server
  • Response#cookie_jar: New in 1.8 An HTTP::CookieJar of cookies
  • Response#request: The RestClient::Request object used to make the request
  • Response#history: New in 2.0 If redirection was followed, a list of prior Response objects
RestClient.get('http://example.com')
 <RestClient::Response 200 "<!doctype h...">

begin
 RestClient.get('http://example.com/notfound')
rescue RestClient::ExceptionWithResponse => err
  err.response
end
 <RestClient::Response 404 "<!doctype h...">

Response callbacks, error handling

A block can be passed to the RestClient method. This block will then be called with the Response. Response.return! can be called to invoke the default response's behavior.

# Don't raise exceptions but return the response
>> RestClient.get('http://example.com/nonexistent') {|response, request, result| response }
=> <RestClient::Response 404 "<!doctype h...">
# Manage a specific error code
RestClient.get('http://example.com/resource') { |response, request, result, &block|
  case response.code
  when 200
    p "It worked !"
    response
  when 423
    raise SomeCustomExceptionIfYouWant
  else
    response.return!(&block)
  end
}

But note that it may be more straightforward to use exceptions to handle different HTTP error response cases:

begin
  resp = RestClient.get('http://example.com/resource')
rescue RestClient::Unauthorized, RestClient::Forbidden => err
  puts 'Access denied'
  return err.response
rescue RestClient::ImATeapot => err
  puts 'The server is a teapot! # RFC 2324'
  return err.response
else
  puts 'It worked!'
  return resp
end

For GET and HEAD requests, rest-client automatically follows redirection. For other HTTP verbs, call .follow_redirection on the response object (works both in block form and in exception form).

# Follow redirections for all request types and not only for get and head
# RFC : "If the 301, 302 or 307 status code is received in response to a request other than GET or HEAD,
#        the user agent MUST NOT automatically redirect the request unless it can be confirmed by the user,
#        since this might change the conditions under which the request was issued."

# block style
RestClient.post('http://example.com/redirect', 'body') { |response, request, result|
  case response.code
  when 301, 302, 307
    response.follow_redirection
  else
    response.return!
  end
}

# exception style by explicit classes
begin
  RestClient.post('http://example.com/redirect', 'body')
rescue RestClient::MovedPermanently,
       RestClient::Found,
       RestClient::TemporaryRedirect => err
  err.response.follow_redirection
end

# exception style by response code
begin
  RestClient.post('http://example.com/redirect', 'body')
rescue RestClient::ExceptionWithResponse => err
  case err.http_code
  when 301, 302, 307
    err.response.follow_redirection
  else
    raise
  end
end

Non-normalized URIs

If you need to normalize URIs, e.g. to work with International Resource Identifiers (IRIs), use the Addressable gem (https://github.com/sporkmonger/addressable/) in your code:

  require 'addressable/uri'
  RestClient.get(Addressable::URI.parse("http://www.詹姆斯.com/").normalize.to_str)

Lower-level access

For cases not covered by the general API, you can use the RestClient::Request class, which provides a lower-level API.

You can:

  • specify ssl parameters
  • override cookies
  • manually handle the response (e.g. to operate on it as a stream rather than reading it all into memory)

See RestClient::Request's documentation for more information.

Streaming request payload

RestClient will try to stream any file-like payload rather than reading it into memory. This happens through RestClient::Payload::Streamed, which is automatically called internally by RestClient::Payload.generate on anything with a read method.

>> r = RestClient.put('http://httpbin.org/put', File.open('/tmp/foo.txt', 'r'),
                      content_type: 'text/plain')
=> <RestClient::Response 200 "{\n  \"args\":...">

In Multipart requests, RestClient will also stream file handles passed as Hash (or new in 2.1 ParamsArray).

>> r = RestClient.put('http://httpbin.org/put',
                      {file_a: File.open('a.txt', 'r'),
                       file_b: File.open('b.txt', 'r')})
=> <RestClient::Response 200 "{\n  \"args\":...">

# received by server as two file uploads with multipart/form-data
>> JSON.parse(r)['files'].keys
=> ['file_a', 'file_b']

Streaming responses

Normally, when you use RestClient.get or the lower level RestClient::Request.execute method: :get to retrieve data, the entire response is buffered in memory and returned as the response to the call.

However, if you are retrieving a large amount of data, for example a Docker image, an iso, or any other large file, you may want to stream the response directly to disk rather than loading it in memory. If you have a very large file, it may become impossible to load it into memory.

There are two main ways to do this:

raw_response, saves into Tempfile

If you pass raw_response: true to RestClient::Request.execute, it will save the response body to a temporary file (using Tempfile) and return a RestClient::RawResponse object rather than a RestClient::Response.

Note that the tempfile created by Tempfile.new will be in Dir.tmpdir (usually /tmp/), which you can override to store temporary files in a different location. This file will be unlinked when it is dereferenced.

If logging is enabled, this will also print download progress. New in 2.1: Customize the interval with :stream_log_percent (defaults to 10 for printing a message every 10% complete).

For example:

>> raw = RestClient::Request.execute(
           method: :get,
           url: 'http://releases.ubuntu.com/16.04.2/ubuntu-16.04.2-desktop-amd64.iso',
           raw_response: true)
=> <RestClient::RawResponse @code=200, @file=#<Tempfile:/tmp/rest-client.20170522-5346-1pptjm1>, @request=<RestClient::Request @method="get", @url="http://releases.ubuntu.com/16.04.2/ubuntu-16.04.2-desktop-amd64.iso">>
>> raw.file.size
=> 1554186240
>> raw.file.path
=> "/tmp/rest-client.20170522-5346-1pptjm1"
raw.file.path
=> "/tmp/rest-client.20170522-5346-1pptjm1"

>> require 'digest/sha1'
>> Digest::SHA1.file(raw.file.path).hexdigest
=> "4375b73e3a1aa305a36320ffd7484682922262b3"

block_response, receives raw Net::HTTPResponse

If you want to stream the data from the response to a file as it comes, rather than entirely in memory, you can also pass RestClient::Request.execute a parameter :block_response to which you pass a block/proc. This block receives the raw unmodified Net::HTTPResponse object from Net::HTTP, which you can use to stream directly to a file as each chunk is received.

Note that this bypasses all the usual HTTP status code handling, so you will want to do you own checking for HTTP 20x response codes, redirects, etc.

The following is an example:

File.open('/some/output/file', 'w') {|f|
  block = proc { |response|
    response.read_body do |chunk|
      f.write chunk
    end
  }
  RestClient::Request.execute(method: :get,
                              url: 'http://example.com/some/really/big/file.img',
                              block_response: block)
}

Shell

The restclient shell command gives an IRB session with RestClient already loaded:

$ restclient
>> RestClient.get 'http://example.com'

Specify a URL argument for get/post/put/delete on that resource:

$ restclient http://example.com
>> put '/resource', 'data'

Add a user and password for authenticated resources:

$ restclient https://example.com user pass
>> delete '/private/resource'

Create ~/.restclient for named sessions:

  sinatra:
    url: http://localhost:4567
  rack:
    url: http://localhost:9292
  private_site:
    url: http://example.com
    username: user
    password: pass

Then invoke:

$ restclient private_site

Use as a one-off, curl-style:

$ restclient get http://example.com/resource > output_body

$ restclient put http://example.com/resource < input_body

Logging

To enable logging globally you can:

  • set RestClient.log with a Ruby Logger
RestClient.log = STDOUT
  • or set an environment variable to avoid modifying the code (in this case you can use a file name, "stdout" or "stderr"):
$ RESTCLIENT_LOG=stdout path/to/my/program

You can also set individual loggers when instantiating a Resource or making an individual request:

resource = RestClient::Resource.new 'http://example.com/resource', log: Logger.new(STDOUT)
RestClient::Request.execute(method: :get, url: 'http://example.com/foo', log: Logger.new(STDERR))

All options produce logs like this:

RestClient.get "http://some/resource"
# => 200 OK | text/html 250 bytes
RestClient.put "http://some/resource", "payload"
# => 401 Unauthorized | application/xml 340 bytes

Note that these logs are valid Ruby, so you can paste them into the restclient shell or a script to replay your sequence of rest calls.

Proxy

All calls to RestClient, including Resources, will use the proxy specified by RestClient.proxy:

RestClient.proxy = "http://proxy.example.com/"
RestClient.get "http://some/resource"
# => response from some/resource as proxied through proxy.example.com

Often the proxy URL is set in an environment variable, so you can do this to use whatever proxy the system is configured to use:

  RestClient.proxy = ENV['http_proxy']

New in 2.0: Specify a per-request proxy by passing the :proxy option to RestClient::Request. This will override any proxies set by environment variable or by the global RestClient.proxy value.

RestClient::Request.execute(method: :get, url: 'http://example.com',
                            proxy: 'http://proxy.example.com')
# => single request proxied through the proxy

This can be used to disable the use of a proxy for a particular request.

RestClient.proxy = "http://proxy.example.com/"
RestClient::Request.execute(method: :get, url: 'http://example.com', proxy: nil)
# => single request sent without a proxy

Query parameters

Rest-client can render a hash as HTTP query parameters for GET/HEAD/DELETE requests or as HTTP post data in x-www-form-urlencoded format for POST requests.

New in 2.0: Even though there is no standard specifying how this should work, rest-client follows a similar convention to the one used by Rack / Rails servers for handling arrays, nested hashes, and null values.

The implementation in ./lib/rest-client/utils.rb closely follows Rack::Utils.build_nested_query, but treats empty arrays and hashes as nil. (Rack drops them entirely, which is confusing behavior.)

If you don't like this behavior and want more control, just serialize params yourself (e.g. with URI.encode_www_form) and add the query string to the URL directly for GET parameters or pass the payload as a string for POST requests.

Basic GET params:

RestClient.get('https://httpbin.org/get', params: {foo: 'bar', baz: 'qux'})
# GET "https://httpbin.org/get?foo=bar&baz=qux"

Basic x-www-form-urlencoded POST params:

>> r = RestClient.post('https://httpbin.org/post', {foo: 'bar', baz: 'qux'})
# POST "https://httpbin.org/post", data: "foo=bar&baz=qux"
=> <RestClient::Response 200 "{\n  \"args\":...">
>> JSON.parse(r.body)
=> {"args"=>{},
    "data"=>"",
    "files"=>{},
    "form"=>{"baz"=>"qux", "foo"=>"bar"},
    "headers"=>
    {"Accept"=>"*/*",
        "Accept-Encoding"=>"gzip, deflate",
        "Content-Length"=>"15",
        "Content-Type"=>"application/x-www-form-urlencoded",
        "Host"=>"httpbin.org"},
    "json"=>nil,
    "url"=>"https://httpbin.org/post"}

JSON payload: rest-client does not speak JSON natively, so serialize your payload to a string before passing it to rest-client.

>> payload = {'name' => 'newrepo', 'description': 'A new repo'}
>> RestClient.post('https://api.github.com/user/repos', payload.to_json, content_type: :json)
=> <RestClient::Response 201 "{\"id\":75149...">

Advanced GET params (arrays):

>> r = RestClient.get('https://http-params.herokuapp.com/get', params: {foo: [1,2,3]})
# GET "https://http-params.herokuapp.com/get?foo[]=1&foo[]=2&foo[]=3"
=> <RestClient::Response 200 "Method: GET...">
>> puts r.body
query_string: "foo[]=1&foo[]=2&foo[]=3"
decoded:      "foo[]=1&foo[]=2&foo[]=3"

GET:
  {"foo"=>["1", "2", "3"]}

Advanced GET params (nested hashes):

>> r = RestClient.get('https://http-params.herokuapp.com/get', params: {outer: {foo: 123, bar: 456}})
# GET "https://http-params.herokuapp.com/get?outer[foo]=123&outer[bar]=456"
=> <RestClient::Response 200 "Method: GET...">
>> puts r.body
...
query_string: "outer[foo]=123&outer[bar]=456"
decoded:      "outer[foo]=123&outer[bar]=456"

GET:
  {"outer"=>{"foo"=>"123", "bar"=>"456"}}

New in 2.0: The new RestClient::ParamsArray class allows callers to provide ordering even to structured parameters. This is useful for unusual cases where the server treats the order of parameters as significant or you want to pass a particular key multiple times.

Multiple fields with the same name using ParamsArray:

>> RestClient.get('https://httpbin.org/get', params:
                  RestClient::ParamsArray.new([[:foo, 1], [:foo, 2]]))
# GET "https://httpbin.org/get?foo=1&foo=2"

Nested ParamsArray:

>> RestClient.get('https://httpbin.org/get', params:
                  {foo: RestClient::ParamsArray.new([[:a, 1], [:a, 2]])})
# GET "https://httpbin.org/get?foo[a]=1&foo[a]=2"

Headers

Request headers can be set by passing a ruby hash containing keys and values representing header names and values:

# GET request with modified headers
RestClient.get 'http://example.com/resource', {:Authorization => 'Bearer cT0febFoD5lxAlNAXHo6g'}

# POST request with modified headers
RestClient.post 'http://example.com/resource', {:foo => 'bar', :baz => 'qux'}, {:Authorization => 'Bearer cT0febFoD5lxAlNAXHo6g'}

# DELETE request with modified headers
RestClient.delete 'http://example.com/resource', {:Authorization => 'Bearer cT0febFoD5lxAlNAXHo6g'}

Timeouts

By default the timeout for a request is 60 seconds. Timeouts for your request can be adjusted by setting the timeout: to the number of seconds that you would like the request to wait. Setting timeout: will override both read_timeout: and open_timeout:.

RestClient::Request.execute(method: :get, url: 'http://example.com/resource',
                            timeout: 120)

Additionally, you can set read_timeout: and open_timeout: separately.

RestClient::Request.execute(method: :get, url: 'http://example.com/resource',
                            read_timeout: 120, open_timeout: 240)

Cookies

Request and Response objects know about HTTP cookies, and will automatically extract and set headers for them as needed:

response = RestClient.get 'http://example.com/action_which_sets_session_id'
response.cookies
# => {"_applicatioN_session_id" => "1234"}

response2 = RestClient.post(
  'http://localhost:3000/',
  {:param1 => "foo"},
  {:cookies => {:session_id => "1234"}}
)
# ...response body

Full cookie jar support (new in 1.8)

The original cookie implementation was very naive and ignored most of the cookie RFC standards. New in 1.8: An HTTP::CookieJar of cookies

Response objects now carry a cookie_jar method that exposes an HTTP::CookieJar of cookies, which supports full standards compliant behavior.

SSL/TLS support

Various options are supported for configuring rest-client's TLS settings. By default, rest-client will verify certificates using the system's CA store on all platforms. (This is intended to be similar to how browsers behave.) You can specify an :ssl_ca_file, :ssl_ca_path, or :ssl_cert_store to customize the certificate authorities accepted.

SSL Client Certificates

RestClient::Resource.new(
  'https://example.com',
  :ssl_client_cert  =>  OpenSSL::X509::Certificate.new(File.read("cert.pem")),
  :ssl_client_key   =>  OpenSSL::PKey::RSA.new(File.read("key.pem"), "passphrase, if any"),
  :ssl_ca_file      =>  "ca_certificate.pem",
  :verify_ssl       =>  OpenSSL::SSL::VERIFY_PEER
).get

Self-signed certificates can be generated with the openssl command-line tool.

Hook

RestClient.add_before_execution_proc add a Proc to be called before each execution. It's handy if you need direct access to the HTTP request.

Example:

# Add oauth support using the oauth gem
require 'oauth'
access_token = ...

RestClient.add_before_execution_proc do |req, params|
  access_token.sign! req
end

RestClient.get 'http://example.com'

More

Need caching, more advanced logging or any ability provided by Rack middleware?

Have a look at rest-client-components: http://github.com/crohr/rest-client-components

Credits

REST Client Team Andy Brody
Creator Adam Wiggins
Maintainers Emeriti Lawrence Leonard Gilbert, Matthew Manning, Julien Kirch
Major contributions Blake Mizerany, Julien Kirch

A great many generous folks have contributed features and patches. See AUTHORS for the full list.

Legal

Released under the MIT License: https://opensource.org/licenses/MIT

Photo of the International Space Station was produced by NASA and is in the public domain.

Code for reading Windows root certificate store derived from work by Puppet; used under terms of the Apache License, Version 2.0.

rest-client's People

Contributors

ab avatar acrogenesis avatar adamhjk avatar alext avatar archiloque avatar bmizerany avatar bradediger avatar campo avatar crohr avatar dbackeus avatar deitch avatar dmitri-d avatar francois avatar jcoyne avatar jeg2 avatar jonrowe avatar jrafanie avatar kachick avatar l2g avatar macournoyer avatar mattmanning avatar niko avatar pastorius avatar pchambino avatar rafaelss avatar redbar0n avatar technoweenie avatar tmm1 avatar xaviershay avatar zapnap avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

rest-client's Issues

Problem w/ array param w/ hash elements

I ran into what seems to be a bug when attempting to pass an array of hashes as a parameter to RestClient.post (in the context of sending an array of objects represented as a hashes of attribute names / values).

Issuing the following request:

RestClient.post 'http://localhost:3000/test', :'attrs[]' => [{:foo => 'bar'}, {:foo => 'money'}]

and handling it w/ the following sinatra callback

post '/test' do
puts "#{params.inspect}"
end

prints out

{"attrs"=>["foobar", "foomoney"]}

when I am looking for

{"attrs" => [{"foo" => 'bar'}, {"foo" => 'money'}]

Is this a bug w/ rest-client or an issue on my part? Thanks alot.

Handle array parameter values

RestClient does not handle parameter values that are Arrays. Typically this translates into a query parameter that looks like this:

:q => [1,2,3]

into this:

?q=1&q=2&q=3

Specifically this patch does it (request.rb line 75):

      query_string = get_params.collect do |k, v|
        if v.is_a?(Array)
          v.map do |x|
            "#{k.to_s}=#{CGI::escape(x.to_s)}" 
          end.join('&')
        else
          "#{k.to_s}=#{CGI::escape(v.to_s)}" 
        end
      end.join('&')

Facebook Graph API Access Tokens are not recognized as valid URI

URIs that contain Access Tokens as used by Facebook's new Graph API are not recognized as valid.

For example, in an irb session (yup, there is a dot in the end of that URI...):

>> r = RestClient.get 'http://graph.facebook.com/btaylor?access_token=2227470867|2.4ZGC2oYAumfR2sqhRORCfA__.3600.1272560400-663966986|vB4dVnF6rhyh6QDJmwfEgmKvKlE.'
URI::InvalidURIError: bad URI(is not URI?): http://graph.facebook.com/btaylor?access_token=2227470867|2.4ZGC2oYAumfR2sqhRORCfA__.3600.1272560400-663966986|vB4dVnF6rhyh6QDJmwfEgmKvKlE.

The Exception class extends nil with a method_missing which causes a stack overflow if nil is called with an undefined method

In the Exception#initialize exceptions.rb, rest-client extends the response given with a module which includes a method_missing which makes the rest-client response compatible with net http response.

If later nil is called with an undefined method, it throws ruby into an infinite loop because it's trying to grab the net_http_res of nil so that it can call respond_to? on it.

Incorrect redirect processing

When following redirects, RestClient blindly rewrites the original request into a GET request. The HTTP 1.1 specification explicitly forbids automatic redirect for most cases if the original request is not a GET or HEAD.

From http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html :

"If the 301 status code is received in response to a request other than GET or HEAD, the user agent MUST NOT automatically redirect the request unless it can be confirmed by the user, since this might change the conditions under which the request was issued.

Note: When automatically redirecting a POST request after receiving a 301 status code, some existing HTTP/1.0 user agents will erroneously change it into a GET request."

TypeError: can't convert RestClient::Payload::Base into String

The calling code is:

fb_response = RestClient.post(@fb_url, req_xml, :content_type=>:xml)

That's correct right?

And the backtrace is:

TypeError: can't convert RestClient::Payload::Base into String
    /usr/local/lib/ruby/site_ruby/1.9.1/openssl/buffering.rb:227:in `do_write'
    /usr/local/lib/ruby/site_ruby/1.9.1/openssl/buffering.rb:249:in `write'
    /usr/local/lib/ruby/1.9.1/net/protocol.rb:191:in `write0'
    /usr/local/lib/ruby/1.9.1/net/protocol.rb:167:in `block in write'
    /usr/local/lib/ruby/1.9.1/net/protocol.rb:182:in `writing'
    /usr/local/lib/ruby/1.9.1/net/protocol.rb:166:in `write'
    /usr/local/lib/ruby/gems/1.9.1/gems/http_connection-1.3.0/lib/net_fix.rb:98:in `send_request_with_body'
    /usr/local/lib/ruby/gems/1.9.1/gems/http_connection-1.3.0/lib/net_fix.rb:83:in `exec'
    /usr/local/lib/ruby/gems/1.9.1/gems/http_connection-1.3.0/lib/net_fix.rb:144:in `request'
    /usr/local/lib/ruby/gems/1.9.1/gems/rest-client-1.6.1/lib/restclient/request.rb:167:in `block in transmit'
    /usr/local/lib/ruby/1.9.1/net/http.rb:627:in `start'
    /usr/local/lib/ruby/gems/1.9.1/gems/rest-client-1.6.1/lib/restclient/request.rb:166:in `transmit'
    /usr/local/lib/ruby/gems/1.9.1/gems/rest-client-1.6.1/lib/restclient/request.rb:60:in `execute'
    /usr/local/lib/ruby/gems/1.9.1/gems/rest-client-1.6.1/lib/restclient/request.rb:31:in `execute'
    /usr/local/lib/ruby/gems/1.9.1/gems/rest-client-1.6.1/lib/restclient.rb:72:in `post'
    /mnt/appoxy_grid/projects/cdecdeca-b4ce-11df-8dec-123139141148/app.rb:38:in `block in <class:MyApp>'

This is in Ruby 1.9.2, not sure if the same occurs in 1.9.1

Restclient runtime error on ruby 1.9.2.p0

Trying to invoke the restclient shell.

owain@/Users/owain/dev/p1$ restclient
/Users/owain/.rvm/gems/ruby-1.9.2-p0@rails3/gems/rest-client-1.6.1/bin/restclient:36:in `r': can't modify frozen object (RuntimeError)
    from /Users/owain/.rvm/gems/ruby-1.9.2-p0@rails3/gems/rest-client-1.6.1/bin/restclient:64:in `method_missing'
    from :29:in `require'
    from :29:in `require'
    from /Users/owain/.rvm/gems/ruby-1.9.2-p0@rails3/gems/rest-client-1.6.1/bin/restclient:73:in `'
    from /Users/owain/.rvm/gems/ruby-1.9.2-p0@rails3/bin/restclient:19:in `load'
    from /Users/owain/.rvm/gems/ruby-1.9.2-p0@rails3/bin/restclient:19:in `'

The offending method and method call appears to be:

def r
  @r ||= RestClient::Resource.new(@url, @username, @password)
end

r # force rc to load

[PATCH] Allow RestClient to stream payloads from Files, Tempfiles and more

I'm working on a CouchDB library that uses RestClient and CouchDB allows users to send files to the database with a simple PUT command.

The PUT command isn't a multipart form, but the HTTP payload is simply the file's contents.

To upload the file right now with RestClient, I have to read in the file and convert it to a string, but with a small modification I was able to add a new Payload type "Streamed" which simply sets the Payload's @stream to the stream that's passed into to Payload.generate.

This Payload type just overrides the #size method so that it works with File objects that provide stat.size and for objects of classes like StringIO and Tempfile that provide just a size method.

Here is my modification:

http://github.com/caleb/rest-client/commit/6f3a5055bad116c2ee945fde9bd3ea946ef2e152

What do you think?

lib/rest-client.rb not included in gemspec

Therefore the gem can't load in e.g. Rails using config.gem "rest-client"

--- a/rest-client.gemspec
+++ b/rest-client.gemspec
@@ -19,6 +19,7 @@ Gem::Specification.new do |s|
"VERSION",
"bin/restclient",
"lib/rest_client.rb",

  •      "lib/rest-client.rb",
       "lib/restclient.rb",
       "lib/restclient/exceptions.rb",
       "lib/restclient/abstract_response.rb",
    

RestClient breaks uploaded files

I'm trying to upload some files into CouchDB through RestClient but every uploading file is broken.

irb(main):001:0> require 'restclient'
=> true
irb(main):002:0> puts RestClient.put 'http://localhost:5984/test/2800f191127269544ba41da2f61fd572/test.psd?rev=1-57cd04a9cba53c9230093bba73742594', :file => File.new('test.psd')
{"ok":true,"id":"2800f191127269544ba41da2f61fd572","rev":"2-cb64f5ed963d72e1d3238fd6733f6d21"}
=> nil

The file has been changed and the one contains the following text at the beginning of file:

--154081

Content-Disposition: form-data; name="file"; filename="test.psd"

Content-Type: text/plain

Cookies bug

I got error that client doesn't support cookies when trying to issue this command:
RestClient.get "http://vip.hr"

redirection with method post

I need redirection with method post.
The server send me 302 in response to post and a have to load a newn page with method get

This is a patch that work. in module AbstractResponse:
def return! request = nil, result = nil, & block
if (200..207).include? code
self
elsif [301, 302, 307].include? code
unless [:get, :head, :post].include? args[:method]
raise Exceptions::EXCEPTIONS_MAP[code].new(self, code)
else
args[:method] = :get if args[:method] == :get
follow_redirection(request, result, & block)
end
elsif code == 303
args[:method] = :get
args.delete :payload
follow_redirection(request, result, & block)
elsif Exceptions::EXCEPTIONS_MAP[code]
raise Exceptions::EXCEPTIONS_MAP[code].new(self, code)
else
raise RequestFailed self
end
end

Thanks

lib/rest-client.rb not included in gemspec

Therefore the gem can't load in e.g. Rails using config.gem "rest-client"

--- a/rest-client.gemspec
+++ b/rest-client.gemspec
@@ -19,6 +19,7 @@ Gem::Specification.new do |s|
           "VERSION",
           "bin/restclient",
           "lib/rest_client.rb",
+          "lib/rest-client.rb",
           "lib/restclient.rb",
           "lib/restclient/exceptions.rb",
           "lib/restclient/abstract_response.rb",

Which branch, which version ?

Hi

I've noticed that there is a new version on Gemcutter : 1.3.0. I was looking for changes so I went on the GitHub page and looked in the commit history. By the way it would be great to have a simple (at least) History or Changelog file to summarize the changes between version.

I don't understand what commits are in the gem on Gemcutter. I suspect this is the "master" branch that is built for Gemcutter, but there is also a "1.3.0" branch.
For example, the commit 619e1bf seems to be in the "master" branch history, but I can't find the corresponding code in the gem downloaded from Gemcutter.

Do you have any enlightenment about this ?

Thanks

Error with ruby 1.9.2: Can't modify frozen object

I get this error openenin the shell restclient in ruby 1.9.2:

restclient
/home/jmcervera/.rvm/gems/ruby-1.9.2-p0@rails2/gems/rest-client-1.6.1/bin/restclient:36:in r': can't modify frozen object (RuntimeError) from /home/jmcervera/.rvm/gems/ruby-1.9.2-p0@rails2/gems/rest-client-1.6.1/bin/restclient:64:inmethod_missing'
from internal:lib/rubygems/custom_require:29:in require' from <internal:lib/rubygems/custom_require>:29:inrequire'
from /home/jmcervera/.rvm/gems/ruby-1.9.2-p0@rails2/gems/rest-client-1.6.1/bin/restclient:73:in <top (required)>' from /home/jmcervera/.rvm/gems/ruby-1.9.2-p0@rails2/bin/restclient:19:inload'
from /home/jmcervera/.rvm/gems/ruby-1.9.2-p0@rails2/bin/restclient:19:in `

'

Caching

See if we can add a simple caching mechanism for get requests

can't convert RestClient::Response into String

Hi,

It's half a surprise because the history.md file says that there is a change in how the response is formatted, but there is no pointer on what we should change in our implementation.

Also, the version change is just "minor". It is advised to update the major version number if there is a backward incompatibility in the public API (cf. http://semver.org/)

User and password are not CGI.unescape'd

Hi,

when using usernames and passwords containing HTTP's chars (like :, / and - most common: @), you have to escape those chars for using them in an URI, e.g. @ => %40.

URI.parse doesn't do that for us, but RestClient::Request#parse_url_with_auth does neither. As a result I cannot make authenticated requests with a [email protected] username.

Patch is at lgierth/rest-client@f20c5de4702090c8dbc5292e96850eede682e03f

Best regards,
Lars

BadRequest exception hides relevant details

One API I'm working with responds with a 400 response for a large variety of errors, but includes XML data in the response describing in detail the problem. For example:

<?xml version="1.0" encoding="utf-8"?><Error code="400" description="Bad Request" message="One or more fields are invalid; Invalid Field Validation Message : An existing Customer record has been found" />

Right now, this response is hidden behind the exception raised by rest-client, however. All I see in a case like above is:
Exception `RestClient::BadRequest' at C:/Ruby/lib/ruby/gems/1.9.1/gems/rest-client-1.5.1/lib/restclient/abstract_response.rb:53 - Bad Request

It would be nice to have the to_s representation of RestClient::ExceptionWithResponse (and its descendants) include the response body.

Problem with nested parameters

Hi,

I'm trying to do a post request with nested parameters, e.g.

RestClient.post "url", {:foo => {:bar1 => "bar1", :bar2 => "bar2"}}, {:cookies => @cookie}

For some reason only the first one of those nested parameters goes through. Thus, the parameters that the API behind the url receives are {:foo => {:bar1 => "bar1"}}. This seems like a bug to me since the same code worked with all the previous versions. Any idea on what causes this?

undefined method `body' for nil:NilClass (NoMethodError) on nil @response in RestClient::Exception

Sometimes RestClient initializes a RestClient::Exception instance with a nil @response value. If you call http_code on this instance nil is returned because of:

def http_code
  # return integer for compatibility
  @response.code.to_i if @response
end

But if you call http_body you get an "undefined method `body' for nil:NilClass (NoMethodError)" because http_body doees not have the "if @response" guard:

def http_body
  @response.body
end

Shouldn't http_body have this guard as well?

Response cookies calls CGI::Cookie::parse which unescapes cookies, they are never re-escaped

AbstractResponse.cookies calls CGI::Cookie::parse on the cookie values:

http://github.com/archiloque/rest-client/blob/1.5.1/lib/restclient/abstract_response.rb#L26

However, if you have a cookie value like:

BAh7BzoNYXBwX25hbWUiEGFwcGxpY2F0aW9uOgpsb2dpbiIKYWRtaW4%3D%0A--08114ba654f17c04d20dcc5228ec672508f738ca

It will get parsed with a '\n' character response.cookies:

BAh7BzoNYXBwX25hbWUiEGFwcGxpY2F0aW9uOgpsb2dpbiIKYWRtaW4=\n--08114ba654f17c04d20dcc5228ec672508f738ca

When the cookies are passed into another request, they are not re-escaped and the server rejects the cookie, therefore this code wouldn't work:

  res = RestClient.post(
    "http://localhost/login",
     {:login => login, :password => password}.to_json, :content_type => :json)
  RestClient.post("http://localhost/some_auth_route",'',{:cookies => res.cookies})

Is this expected behavior or is there another way to use cookies in a series of requests?

According to this bug report, http://redmine.ruby-lang.org/issues/show/2124, CGI::Cookie.parse should not be used client-side.

Passing parameters in a DELETE request

I have to send an API key with a delete request. It seems that rest-client 1.6.1 wasn't sending those params. I made a modification to /lib/restclient/request.rb at line 65 to include the addition of parameters with delete requests, as you have it for get and head. So this:

if [:get, :head].include? method

becomes this

if [:get, :head, :delete].include? method

Can this be updated in the main trunk?

Cheers,
Aaron.

parenthesize argument(s) for future version

Hi,

I'm getting a warning (see below) on requiring the rest-client.

/Library/Ruby/Gems/1.8/gems/rest-client-1.6.1/lib/restclient/abstract_response.rb:50: warning: parenthesize argument(s) for future version

It's just a warning but unnecessary IMHO.

Changing

raise RequestFailed self

into

raise RequestFailed(self)

should fix it.

bug in cookies

if a set-cookie comes in like this:

sdid=ZJ/HQVH6YE+rVkTpn0zvTQ==

key, *val = cookie.split(";").first.split("=")
out[key] = val.join("=")

will return

sdid=ZJ/HQVH6YE+rVkTpn0zvTQ
because the split doesn't preserve the empty entries, I think this'll work:

data = cookie.split(";").first.match(/(.?)=(.)/)
out[data[1]] = data[2]

When setting multiple cookies on a Request, the "Cookie" header is malformed

When multiple cookies are set on a request, the "Cookie" header concatenates the key/value pairs using commas ( , ). It should be using a semi-colon instead, as per http://www.ietf.org/rfc/rfc2109.txt (Section 4.1)

RestClient.log=($stderr)
RestClient.get( "http://google.ca", { :cookies => { :bruno => "gentil", :laurent => "gentil" } })

Output:

RestClient.get "http://google.ca", "Accept-encoding"=>"gzip, deflate", "Cookie"=>"bruno=gentil,laurent=gentil", "Accept"=>"*/*; q=0.5, application/xml"

Problem is on line 60 of lib/restclient/request.rb:

    user_headers[:cookie] = @cookies.map {|(key, val)| "#{key.to_s}=#{val}" }.sort.join(";")

#<NoMethodError: undefined method `empty?' for nil:NilClass>

Hello,
I'm doing the following (issuing a PUT request against RIAK server) and am receiving a undefined method `empty?' for nil:NilClass> exception from a 204 response code.

RestClient.put "http://127.0.0.1:8091/raw/patents/#{patent["doc_number"]}", patent.to_json, :content_type => :json
RestClient.put "http://127.0.0.1:8091/raw/patents/D0607626", 172 byte length, "Accept"=>"/; q=0.5, application/xml", "Accept-encoding"=>"gzip, deflate", "Content-type"=>"application/json", "Content-Length"=>"172"

=> 204 NoContent | application/json 0 bytes

The PUT request succeeds (i.e. I can see my object in RIAK with the correct content) but each time an exception is raised.

Am I doing something wrong with RestClient?

Question: where to put api key

I need to pass a hash (api key) someplace in the request. Where is the best place for that? :cookie data, as a param? I'm a bit fuzzy on that and didn't see an example illustrating that form of authentication.

Thanks in advance.

Backwards-incompatible change in 1.3.0

Getting (in the heroku client)

./bin/../lib/heroku/client.rb:189:in console': undefined methodbody' for #RestClient::Response:0x101f7bfa0 (NoMethodError)
from ./bin/../lib/heroku/commands/app.rb:139:in console_session' from ./bin/../lib/heroku/commands/app.rb:128:inconsole'
from ./bin/../lib/heroku/command.rb:45:in send' from ./bin/../lib/heroku/command.rb:45:inrun_internal'
from ./bin/../lib/heroku/command.rb:17:in `run'
from bin/heroku:14

I can't figure out where body exists in 1.2.0, but it works there.

Getting the response body even if it's an HTTP error

Hi,

I'm consuming a WebService via RestClient.
Sometimes, I don't give the good params in the POST payload and I get an HTTP error with a response body indicating the error.

The WebService may be wrong giving me a standard HTTP Error with the real value in the response body, but there it is and it would be cool to be able to get it.

Thank you very much for maintaing this very good piece of software that RestClient is.

Sincerly
Jeremy

Should handle multiple attributes inside a hash

It seems like even the simplest typical usage of an objects attributes as a hash fails in the current rest-client.

RestClient.post "http://localhost:3000/movies", :movie => {:title => "Foo", :description => "Bar"}

Will only send the title but not the description.

Example of a failing test for payload_spec.rb

it "should handle many attributes inside a hash" do
  parameters = RestClient::Payload::UrlEncoded.new({:foo => {:bar => 'baz', :baz => 'qux'}}).to_s
  parameters.should include("foo[bar]=baz", "foo[baz]=qux")
end

I recall this working in the old branch of rest-client. The one that didn't have multipart etc.

Library require

Being that the library is called "rest-client", there should probably either a single way to require the library (exactly the same as the name of the library itself) or add "rest-client.rb" to ./lib.

This becomes an annoying quirk when using something like bundler and expecting that the name itself should just work. Its always bothered me knowing that there is restclient and rest_client but no rest-client

Log format when using Ruby logger

When setting RestClient.log = Logger.new(STDOUT), why does the REST client log in a different format than all my other logger calls? I was expecting something like this:

E, [2010-06-28T10:06:54.553160 #10062] ERROR -- : whatever

Basic Authentication does not survive a redirect

If I first make a GET on a URL with username/password (HTTP basic authentication) and get a redirect back as a response then the username/password will not be used for the subsequent request.

Maybe it's make sense to add also something like HTTPClient and HTTPClient::Resource

With the only difference that there will be no difference in semantic of :get and :post, ... methods, and they both can have payloads?

RestClient (current)

def self.get(url, headers={}, &block)
  Request.execute(:method => :get, :url => url, :headers => headers, &block)
end

def self.post(url, payload, headers={}, &block)
  Request.execute(:method => :post, :url => url, :payload => payload, :headers => headers, &block)
end

HTTPClient < RestClient

def self.get(url, payload = nil, headers={}, &block)
  Request.execute(:method => :get, :url => url, :payload => payload, :headers => headers, &block)
end

def self.post(url, payload = nil, headers={}, &block)
  Request.execute(:method => :post, :url => url, :payload => payload, :headers => headers, &block)
end

I understood that it was made such way in according to ActiveResource routing scheme, but RESTful API not always correspond to such scheme.

What do you think?

Document nested hash payload

I am using rest_client for a Rails project and had to dig around quite a bit, but found the nested payload very useful. I think it would be a good thing to document. This is probably used by any Rails developer with nested models. An example of my code:

RestClient.post( url, 
  { 
    :transfer => {
      :path => '/foo/bar',
      :owner => 'that_guy',
      :group => 'those_guys'
    },
    :upload => {
      :file => File.new(path)
    }
  })

ZLib::Inflate doesn't work for HTTP servers that use raw DEFLATE compression

RestClient::Request.decode assumes that any request body compressed with the DEFLATE compression scheme will have ZLib headers. This is according to spec, but some web servers coughMicrosoft IIScough (see here) return raw DEFLATE data, without the ZLib headers.

Here's a forum post that describes how Mongrel copes with this for browsers that make the same error. I think this will work for RestClient as well:

begin
  Zlib::Inflate.new.inflate body
rescue Zlib::DataError
  # No luck with Zlib decompression. Let's try with raw deflate,
  # like some broken web servers do.
  Zlib::Inflate.new(-Zlib::MAX_WBITS).inflate body;
end

If I have time, I'll test this behaviour against an IIS server and create a patch. In the meantime, I'm creating this issue so I don't forget about it, and to inform others who might run into the same problem.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.