1 package HTTP::Response;
4 @ISA = qw(HTTP::Message);
14 my($class, $rc, $msg, $header, $content) = @_;
15 my $self = $class->SUPER::new($header, $content);
24 my($class, $str) = @_;
26 if ($str =~ s/^(.*)\n//) {
34 my $self = $class->SUPER::parse($str);
35 my($protocol, $code, $message);
36 if ($status_line =~ /^\d{3} /) {
37 # Looks like a response created by HTTP::Response->new
38 ($code, $message) = split(' ', $status_line, 2);
40 ($protocol, $code, $message) = split(' ', $status_line, 3);
42 $self->protocol($protocol) if $protocol;
43 $self->code($code) if defined($code);
44 $self->message($message) if defined($message);
52 my $clone = bless $self->SUPER::clone, ref($self);
53 $clone->code($self->code);
54 $clone->message($self->message);
55 $clone->request($self->request->clone) if $self->request;
56 # we don't clone previous
61 sub code { shift->_elem('_rc', @_); }
62 sub message { shift->_elem('_msg', @_); }
63 sub previous { shift->_elem('_previous',@_); }
64 sub request { shift->_elem('_request', @_); }
70 my $code = $self->{'_rc'} || "000";
71 my $mess = $self->{'_msg'} || HTTP::Status::status_message($code) || "Unknown code";
79 my $base = $self->header('Content-Base') || # used to be HTTP/1.1
80 $self->header('Content-Location') || # HTTP/1.1
81 $self->header('Base'); # HTTP/1.0
82 if ($base && $base =~ /^$URI::scheme_re:/o) {
84 return $HTTP::URI_CLASS->new($base);
87 my $req = $self->request;
89 # if $base is undef here, the return value is effectively
90 # just a copy of $self->request->uri.
91 return $HTTP::URI_CLASS->new_abs($base, $req->uri);
94 # can't find an absolute base
104 my $cd = $self->header('Content-Disposition');
106 require HTTP::Headers::Util;
107 if (my @cd = HTTP::Headers::Util::split_header_words($cd)) {
108 my ($disposition, undef, %cd_param) = @{$cd[-1]};
109 $file = $cd_param{filename};
112 if ($file && $file =~ /^=\?(.+?)\?(.+?)\?(.+)\?=$/) {
114 my $encoding = uc($2);
117 if ($encoding eq 'Q' || $encoding eq 'B') {
118 local($SIG{__DIE__});
120 if ($encoding eq 'Q') {
122 require MIME::QuotedPrint;
123 $encfile = MIME::QuotedPrint::decode($encfile);
125 else { # $encoding eq 'B'
126 require MIME::Base64;
127 $encfile = MIME::Base64::decode($encfile);
132 # This is ugly use of non-public API, but is there
133 # a better way to accomplish what we want (locally
134 # as-is usable filename string)?
135 my $locale_charset = encoding::_get_locale_encoding();
136 Encode::from_to($encfile, $charset, $locale_charset);
139 $file = $encfile unless $@;
146 unless (defined($file) && length($file)) {
147 if (my $cl = $self->header('Content-Location')) {
148 $uri = URI->new($cl);
150 elsif (my $request = $self->request) {
151 $uri = $request->uri;
155 $file = ($uri->path_segments)[-1];
160 $file =~ s,.*[\\/],,; # basename
163 if ($file && !length($file)) {
173 require HTTP::Status;
176 $eol = "\n" unless defined $eol;
178 my $status_line = $self->status_line;
179 my $proto = $self->protocol;
180 $status_line = "$proto $status_line" if $proto;
182 return join($eol, $status_line, $self->SUPER::as_string(@_));
186 sub is_info { HTTP::Status::is_info (shift->{'_rc'}); }
187 sub is_success { HTTP::Status::is_success (shift->{'_rc'}); }
188 sub is_redirect { HTTP::Status::is_redirect (shift->{'_rc'}); }
189 sub is_error { HTTP::Status::is_error (shift->{'_rc'}); }
194 require HTML::Entities;
196 my $title = 'An Error Occurred';
197 my $body = HTML::Entities::encode($self->status_line);
200 <head><title>$title</title></head>
213 # Implementation of RFC 2616 section 13.2.3
215 my $response_time = $self->client_date;
216 my $date = $self->date;
219 if ($response_time && $date) {
220 $age = $response_time - $date; # apparent_age
221 $age = 0 if $age < 0;
224 my $age_v = $self->header('Age');
225 if ($age_v && $age_v > $age) {
226 $age = $age_v; # corrected_received_age
229 my $request = $self->request;
231 my $request_time = $request->date;
233 # Add response_delay to age to get 'corrected_initial_age'
234 $age += $response_time - $request_time;
237 if ($response_time) {
238 $age += time - $response_time;
244 sub freshness_lifetime
248 # First look for the Cache-Control: max-age=n header
249 my @cc = $self->header('Cache-Control');
254 for $cc_dir (split(/\s*,\s*/, $cc)) {
255 if ($cc_dir =~ /max-age\s*=\s*(\d+)/i) {
262 # Next possibility is to look at the "Expires" header
263 my $date = $self->date || $self->client_date || time;
264 my $expires = $self->expires;
266 # Must apply heuristic expiration
267 my $last_modified = $self->last_modified;
268 if ($last_modified) {
269 my $h_exp = ($date - $last_modified) * 0.10; # 10% since last-mod
273 elsif ($h_exp > 24 * 3600) {
274 # Should give a warning if more than 24 hours according to
275 # RFC 2616 section 13.2.4, but I don't know how to do it
276 # from this function interface, so I just make this the
283 return 3600; # 1 hour is fallback when all else fails
286 return $expires - $date;
293 $self->freshness_lifetime > $self->current_age;
300 return $self->freshness_lifetime - $self->current_age + time;
310 HTTP::Response - HTTP style response message
314 Response objects are returned by the request() method of the C<LWP::UserAgent>:
317 $response = $ua->request($request)
318 if ($response->is_success) {
319 print $response->content;
322 print STDERR $response->status_line, "\n";
327 The C<HTTP::Response> class encapsulates HTTP style responses. A
328 response consists of a response line, some headers, and a content
329 body. Note that the LWP library uses HTTP style responses even for
330 non-HTTP protocol schemes. Instances of this class are usually
331 created and returned by the request() method of an C<LWP::UserAgent>
334 C<HTTP::Response> is a subclass of C<HTTP::Message> and therefore
335 inherits its methods. The following additional methods are available:
339 =item $r = HTTP::Response->new( $code )
341 =item $r = HTTP::Response->new( $code, $msg )
343 =item $r = HTTP::Response->new( $code, $msg, $header )
345 =item $r = HTTP::Response->new( $code, $msg, $header, $content )
347 Constructs a new C<HTTP::Response> object describing a response with
348 response code $code and optional message $msg. The optional $header
349 argument should be a reference to an C<HTTP::Headers> object or a
350 plain array reference of key/value pairs. The optional $content
351 argument should be a string of bytes. The meaning these arguments are
354 =item $r = HTTP::Response->parse( $str )
356 This constructs a new response object by parsing the given string.
360 =item $r->code( $code )
362 This is used to get/set the code attribute. The code is a 3 digit
363 number that encode the overall outcome of a HTTP response. The
364 C<HTTP::Status> module provide constants that provide mnemonic names
365 for the code attribute.
369 =item $r->message( $message )
371 This is used to get/set the message attribute. The message is a short
372 human readable single line string that explains the response code.
374 =item $r->header( $field )
376 =item $r->header( $field => $value )
378 This is used to get/set header values and it is inherited from
379 C<HTTP::Headers> via C<HTTP::Message>. See L<HTTP::Headers> for
380 details and other similar methods that can be used to access the
385 =item $r->content( $bytes )
387 This is used to get/set the raw content and it is inherited from the
388 C<HTTP::Message> base class. See L<HTTP::Message> for details and
389 other methods that can be used to access the content.
391 =item $r->decoded_content( %options )
393 This will return the content after any C<Content-Encoding> and
394 charsets have been decoded. See L<HTTP::Message> for details.
398 =item $r->request( $request )
400 This is used to get/set the request attribute. The request attribute
401 is a reference to the the request that caused this response. It does
402 not have to be the same request passed to the $ua->request() method,
403 because there might have been redirects and authorization retries in
408 =item $r->previous( $response )
410 This is used to get/set the previous attribute. The previous
411 attribute is used to link together chains of responses. You get
412 chains of responses if the first response is redirect or unauthorized.
413 The value is C<undef> if this is the first response in a chain.
415 =item $r->status_line
417 Returns the string "E<lt>code> E<lt>message>". If the message attribute
418 is not set then the official name of E<lt>code> (see L<HTTP::Status>)
423 Returns the base URI for this response. The return value will be a
424 reference to a URI object.
426 The base URI is obtained from one the following sources (in priority
433 Embedded in the document content, for instance <BASE HREF="...">
438 A "Content-Base:" or a "Content-Location:" header in the response.
440 For backwards compatibility with older HTTP implementations we will
441 also look for the "Base:" header.
445 The URI used to request this response. This might not be the original
446 URI that was passed to $ua->request() method, because we might have
447 received some redirect responses first.
451 If none of these sources provide an absolute URI, undef is returned.
453 When the LWP protocol modules produce the HTTP::Response object, then
454 any base URI embedded in the document (step 1) will already have
455 initialized the "Content-Base:" header. This means that this method
456 only performs the last 2 steps (the content is not always available
461 Returns a filename for this response. Note that doing sanity checks
462 on the returned filename (eg. removing characters that cannot be used
463 on the target filesystem where the filename would be used, and
464 laundering it for security purposes) are the caller's responsibility;
465 the only related thing done by this method is that it makes a simple
466 attempt to return a plain filename with no preceding path segments.
468 The filename is obtained from one the following sources (in priority
475 A "Content-Disposition:" header in the response. Proper decoding of
476 RFC 2047 encoded filenames requires the C<MIME::QuotedPrint> (for "Q"
477 encoding), C<MIME::Base64> (for "B" encoding), and C<Encode> modules.
481 A "Content-Location:" header in the response.
485 The URI used to request this response. This might not be the original
486 URI that was passed to $ua->request() method, because we might have
487 received some redirect responses first.
491 If a filename cannot be derived from any of these sources, undef is
496 =item $r->as_string( $eol )
498 Returns a textual representation of the response.
504 =item $r->is_redirect
508 These methods indicate if the response was informational, successful, a
509 redirection, or an error. See L<HTTP::Status> for the meaning of these.
511 =item $r->error_as_HTML
513 Returns a string containing a complete HTML document indicating what
514 error occurred. This method should only be called when $r->is_error
517 =item $r->current_age
519 Calculates the "current age" of the response as specified by RFC 2616
520 section 13.2.3. The age of a response is the time since it was sent
521 by the origin server. The returned value is a number representing the
524 =item $r->freshness_lifetime
526 Calculates the "freshness lifetime" of the response as specified by
527 RFC 2616 section 13.2.4. The "freshness lifetime" is the length of
528 time between the generation of a response and its expiration time.
529 The returned value is a number representing the freshness lifetime in
532 If the response does not contain an "Expires" or a "Cache-Control"
533 header, then this function will apply some simple heuristic based on
534 'Last-Modified' to determine a suitable lifetime.
538 Returns TRUE if the response is fresh, based on the values of
539 freshness_lifetime() and current_age(). If the response is no longer
540 fresh, then it has to be refetched or revalidated by the origin
543 =item $r->fresh_until
545 Returns the time when this entity is no longer fresh.
551 L<HTTP::Headers>, L<HTTP::Message>, L<HTTP::Status>, L<HTTP::Request>
555 Copyright 1995-2004 Gisle Aas.
557 This library is free software; you can redistribute it and/or
558 modify it under the same terms as Perl itself.