HTTP_Request2_Response – Class representing a HTTP response message


HTTP_Request2_Response encapsulates a HTTP response message and provides easy access to different parts of it. It also contains static helper methods HTTP_Request2_Response::decodeGzip() and HTTP_Request2_Response::decodeDeflate() for decoding response bodies encoded by Content-Encoding: gzip (as defined in RFC 1952) and Content-Encoding: deflate (RFC 1950), respectively.

An instance of this class will usually be returned by HTTP_Request2::send() method. You can also build an instance yourself using either helper methods of HTTP_Request2_Adapter_Mock or manually (see below).

You can use the following methods for accessing various parts of HTTP response: getStatus(), getReasonPhrase(), getVersion(), getHeader(), getCookies(), getBody(). Note that the response object will not contain the response body if 'store_body' configuration parameter was set to FALSE. Also note that getBody() always returns body completely decoded, if for some reason you want to access body still encoded by gzip / deflate you'll need to use Observers and Socket adapter.

Accessing response parts

= new HTTP_Request2('');
$response $request->send();

"Response status: " $response->getStatus() . "\n";
"Human-readable reason phrase: " $response->getReasonPhrase() . "\n";
"Response HTTP version: " $response->getVersion() . "\n";
"Response headers:\n";
foreach (
$response->getHeader() as $k => $v) {
"Value of a specific header (Content-Type): " $response->getHeader('content-type') . "\n";
"Cookies set in response:\n";
foreach (
$response->getCookies() as $c) {
"\tname: {$c['name']}, value: {$c['value']}.
$c['expires'])? ''", expires: {$c['expires']}") .
$c['domain'])? ''", domain: {$c['domain']}") .
$c['path'])? ''", path: {$c['path']}") .
", secure: " . ($c['secure']? 'yes''no') . "\n";
"Response body:\n" $response->getBody();

Building the Response Manually

The class is designed to be used in "streaming" scenario, building the response as it is being received:

Building the response (pseudocode)

$response = new HTTP_Request2_Response($statusLine);

do {
$headerLine read_header_line();
} while (
$headerLine != '');

while (
$chunk read_body()) {

Everything is straightforward enough, but a few things need considering:

  • Constructor will throw an exception if the provided string does not look like a valid response status line.
  • It is necessary to pass an empty string to parseHeaderLine() to indicate the end of response headers: this triggers some additional processing (e.g. cookie parsing).
Classes that actually perform the request (Previous) Monitoring the request's progress (Next)
Last updated: Fri, 24 Feb 2017 — Download Documentation
Do you think that something on this page is wrong? Please file a bug report.
View this page in:
  • English

User Notes:

There are no user contributed notes for this page.