develooper Front page | perl.libwww | Postings from March 2003

Fwd: Snippet to Uncompress Deflated HTTP Response

From:
david
Date:
March 26, 2003 10:46
Subject:
Fwd: Snippet to Uncompress Deflated HTTP Response
Message ID:
20030326104643.10273.h006.c000.wm@mail.carter.net.criticalpath.net
Should have included this code that calls the sub in
the original post:

if ( $res->header('Content-encoding')) {
			my $encoding = $res->header('Content-encoding');
			if ($encoding =~ /deflate/o ) {
				# process deflate encoding
				print "\ndeflate encoding found\n";
				$res->content(inflateBody($res->content_ref));
			} elsif ($encoding =~ /gzip/o ) {
				# process gzip encoding
				print "\ngzip encoding found\n";
				die "gzip decompression not yet implemented\n";
			} else {
				die "unsuported content-encoding $encoding returned
by browser\n";
			}
		}



------- Start of forwarded message -------

From: david@carter.net
Date: Wed, 26 Mar 2003 10:17:50 -0800 (PST)
Subject: Snippet to Uncompress Deflated HTTP Response
To: libwww@perl.org

Here's a snippet of code I have used to process
deflated HTTP responses. It would be great if this
processing could be handled somewhere in the guts of
LWP!

sub inflateBody {

		my ($body_ref) = @_;
		my $body = $$body_ref;
		
		my $result = undef;
		
		my $deflated_length = length($body);
		my $i = inflateInit( -WindowBits => -15 ) or die
"Cannot create an inflation stream\n" ;
		($result, my $status) = $i->inflate($body);
		if ($status == Z_OK or $status == Z_STREAM_END) {
			my $inflated_length = length($result);
			my $compression_ratio = int((1 -
$deflated_length/$inflated_length) * 100);
			print "\nContent-length after inflate =
$inflated_length  savings = $compression_ratio%\n\n";
			#decode_entities($result); # get rid of HTML
entities ("&" etc.)
			#if (length($result) <= 1024) { # only print the
small ones (redirects)
			#	print "\nBody =\n$result\n";
			#} 
		} else {
			print "\nInflation failed: status = $status\n";
			print "\nBody length after failed inflate =
",length($result),"\n";
			print "\n1st 40 body char codes after failed inflate
=\n";
			for (my $j=0;$j<39;$j++) {
				print ord(substr($body,$j,1)), " ";
			}
			print "\n";
			if (defined($result)) { print "\nInflated body =
$result\n";}
		}
		return $result;
}

------- End of forwarded message -------



nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About