1
0
Fork 0
mirror of https://github.com/jnunemaker/httparty synced 2023-03-27 23:23:07 -04:00

Automatically inflate deflated responses

This commit is contained in:
Sandro Turriate 2010-06-09 19:00:41 -04:00
parent b515d68270
commit d950d38d3a
5 changed files with 39 additions and 2 deletions

View file

@ -0,0 +1,12 @@
Feature: Handles Compressed Responses
In order to save bandwidth
As a developer
I want to uncompress compressed responses
Scenario: Supports deflate encoding
Given a remote deflate service
And the response from the service has a body of '<h1>Some HTML</h1>'
And that service is accessed at the path '/service.html'
When I call HTTParty#get with '/service.html'
Then the return value should match '<h1>Some HTML</h1>'

View file

@ -22,6 +22,15 @@ class BasicMongrelHandler < Mongrel::HttpHandler
end
end
class DeflateHandler < BasicMongrelHandler
def process(request, response)
response.start do |head, body|
head['Content-Encoding'] = 'deflate'
body.write Zlib::Deflate.deflate(response_body)
end
end
end
module BasicAuthentication
def self.extended(base)
base.custom_headers["WWW-Authenticate"] = 'Basic Realm="Super Secret Page"'

View file

@ -17,6 +17,10 @@ Given /^that service takes (\d+) seconds to generate a response$/ do |time|
@handler.preprocessor = lambda { sleep time.to_i }
end
Given /^a remote deflate service$/ do
@handler = DeflateHandler.new
end
Given /the response from the service has a Content-Type of '(.*)'/ do |content_type|
@handler.content_type = content_type
end

View file

@ -1,6 +1,8 @@
require 'pathname'
require 'net/http'
require 'net/https'
require 'uri'
require 'zlib'
require 'crack'
dir = Pathname(__FILE__).dirname.expand_path

View file

@ -1,5 +1,3 @@
require 'uri'
module HTTParty
class Request #:nodoc:
SupportedHTTPMethods = [
@ -144,6 +142,7 @@ module HTTParty
# Raises exception Net::XXX (http error code) if an http error occured
def handle_response
handle_deflation
case last_response
when Net::HTTPMultipleChoice, # 300
Net::HTTPMovedPermanently, # 301
@ -166,6 +165,17 @@ module HTTParty
end
end
# Inspired by Ruby 1.9
def handle_deflation
case last_response["content-encoding"]
when "gzip"
body_io = StringIO.new(last_response.body)
last_response.body.replace Zlib::GzipReader.new(body_io).read
when "deflate"
last_response.body.replace Zlib::Inflate.inflate(last_response.body)
end
end
def parse_response(body)
parser.call(body, format)
end