HTTP Client - Overview

Overview

Zend\Http\Client provides an easy interface for performing Hyper-Text Transfer Protocol (HTTP) requests. Zend\Http\Client supports the most simple features expected from an HTTP client, as well as some more complex features such as HTTP authentication and file uploads. Successful requests (and most unsuccessful ones too) return a Zend\Http\Response object, which provides access to the response’s headers and body (see this section).

Quick Start

The class constructor optionally accepts a URL as its first parameter (can be either a string or a Zend\Uri\Http object), and an array or Zend\Config\Config object containing configuration options. Both can be left out, and set later using the setUri() and setConfig() methods.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
use Zend\Http\Client;
$client = new Client('http://example.org', array(
    'maxredirects' => 0,
    'timeout'      => 30
));

// This is actually exactly the same:
$client = new Client();
$client->setUri('http://example.org');
$client->setOptions(array(
    'maxredirects' => 0,
    'timeout'      => 30
));

// You can also pass a Zend\Config\Config object to set the client's configuration
$config = Zend\Config\Factory::fromFile('httpclient.ini');
$client->setOptions($config);

Note

Zend\Http\Client uses Zend\Uri\Http to validate URLs. See the Zend\Uri manual page for more information on the validation process.

Configuration Options

The constructor and setOptions() method accept an associative array of configuration parameters, or a Zend\Config\Config object. Setting these parameters is optional, as they all have default values.

Zend\Http\Client configuration parameters
Parameter Description Expected Values Default Value
maxredirects Maximum number of redirections to follow (0 = none) integer 5
strictredirects Whether to strictly follow the RFC when redirecting (see this section) boolean FALSE
useragent User agent identifier string (sent in request headers) string ‘Zend\Http\Client’
timeout Connection timeout (seconds) integer 10
httpversion HTTP protocol version (usually ‘1.1’ or ‘1.0’) string ‘1.1’
adapter Connection adapter class to use (see this section) mixed ‘Zend\Http\Client\Adapter\Socket’
keepalive Whether to enable keep-alive connections with the server. Useful and might improve performance if several consecutive requests to the same server are performed. boolean FALSE
storeresponse Whether to store last response for later retrieval with getLastResponse(). If set to FALSE, getLastResponse() will return NULL. boolean TRUE
encodecookies Whether to pass the cookie value through urlencode/urldecode. Enabling this breaks support with some web servers. Disabling this limits the range of values the cookies can contain. boolean TRUE
outputstream Destination for streaming of received data (options: string (filename), true for temp file, false/null to disable streaming) boolean FALSE
rfc3986strict Whether to strictly adhere to RFC 3986 (in practice, this means replacing ‘+’ with ‘%20’) boolean FALSE

Available Methods

__construct

__construct(string $uri, array|Traversable $config)

Constructor

Returns void

setOptions

setOptions(array|Traversable $config = array ())

Set configuration parameters for this HTTP client

Returns Zend\Http\Client

setAdapter

setAdapter(Zend\Http\Client\Adapter|string $adapter)

Load the connection adapter

While this method is not called more than once for a client, it is separated from ->send() to preserve logic and readability

Returns Zend\Http\Client

getAdapter

getAdapter()

Retrieve the connection adapter

Returns Zend\Http\Client\Adapter\AdapterInterface

setRequest

setRequest(Zend\Http\Request $request)

Set request object

Returns void

getRequest

getRequest()

Get Request object

Returns Zend\Http\Request

getLastRawRequest

getLastRawRequest()

Get the last request (as a string)

Returns string

setResponse

setResponse(Zend\Http\Response $response)

Set response

Returns Zend\Http\Client

getResponse

getResponse()

Get Response object

Returns Zend\Http\Response

getLastRawResponse

getLastRawResponse()

Get the last response (as a string)

Returns string

getRedirectionsCount

getRedirectionsCount()

Get the redirections count

Returns integer

setUri

setUri(string|Zend\Http\Zend\Uri\Http $uri)

Set Uri (to the request)

Returns Zend\Http\Client

getUri

getUri()

Get uri (from the request)

Returns Zend\Uri\Http

setMethod

setMethod(string $method)

Set the HTTP method (to the request)

Returns Zend\Http\Client

getMethod

getMethod()

Get the HTTP method

Returns string

setEncType

setEncType(string $encType, string $boundary)

Set the encoding type and the boundary (if any)

Returns void

getEncType

getEncType()

Get the encoding type

Returns type

setRawBody

setRawBody(string $body)

Set raw body (for advanced use cases)

Returns Zend\Http\Client

setParameterPost

setParameterPost(array $post)

Set the POST parameters

Returns Zend\Http\Client

setParameterGet

setParameterGet(array $query)

Set the GET parameters

Returns Zend\Http\Client

getCookies

getCookies()

Return the current cookies

Returns array

setCookies

setCookies(array $cookies)

Set an array of cookies

Returns Zend\Http\Client

clearCookies

clearCookies()

Clear all the cookies

Returns void

setHeaders

setHeaders(Zend\Http\Headers|array $headers)

Set the headers (for the request)

Returns Zend\Http\Client

hasHeader

hasHeader(string $name)

Check if exists the header type specified

Returns boolean

getHeader

getHeader(string $name)

Get the header value of the request

Returns string|boolean

setStream

setStream(string|boolean $streamfile = true)

Set streaming for received data

Returns Zend\Http\Client

getStream

getStream()

Get status of streaming for received data

Returns boolean|string

setAuth

setAuth(string $user, string $password, string $type = 'basic')

Create a HTTP authentication “Authorization:” header according to the specified user, password and authentication method.

Returns Zend\Http\Client

resetParameters

resetParameters()

Reset all the HTTP parameters (auth,cookies,request, response, etc)

Returns void

dispatch

dispatch(Zend\Stdlib\RequestInterface $request, Zend\Stdlib\ResponseInterface $response= null)

Dispatch HTTP request

Returns Response

send

send(Zend\Http\Request $request)

Send HTTP request

Returns Response

setFileUpload

setFileUpload(string $filename, string $formname, string $data = null, string $ctype = null)

Set a file to upload (using a POST request)

Can be used in two ways: 1. $data is null (default): $filename is treated as the name if a local file which will be read and sent. Will try to guess the content type using mime_content_type(). 2. $data is set - $filename is sent as the file name, but $data is sent as the file contents and no file is read from the file system. In this case, you need to manually set the Content-Type ($ctype) or it will default to application/octet-stream.

Returns Zend\Http\Client

removeFileUpload

removeFileUpload(string $filename)

Remove a file to upload

Returns boolean

encodeFormData

encodeFormData(string $boundary, string $name, mixed $value, string $filename = null, array $headers = array ( ))

Encode data to a multipart/form-data part suitable for a POST request.

Returns string

Examples

Performing a Simple GET Request

Performing simple HTTP requests is very easily done using the setRequest() and dispatch() methods:

1
2
3
4
5
6
7
use Zend\Http\Client;
use Zend\Http\Request;

$request = new Request();
$client = new Client('http://example.org');
$client->setRequest($request);
$response = $client->dispatch();

The request object can be configured using his methods as shown in the Zend\Http\Request manual page. One of these methods is setMethod which refers to the HTTP Method. This can be either GET, POST, PUT, HEAD, DELETE, TRACE, OPTIONS or CONNECT as defined by the HTTP protocol [1].

Using Request Methods Other Than GET

For convenience, these are all defined as class constants: Zend\Http\Request::METHOD_GET, Zend\Http\Request::METHOD_POST and so on.

If no method is specified, the method set by the last setMethod() call is used. If setMethod() was never called, the default request method is GET (see the above example).

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
use Zend\Http\Client;
use Zend\Http\Request;

$request = new Request();
$request->setUri('http://example.org');
$client = new Client();

// Performing a POST request
$request->setMethod(Request::METHOD_POST);
$client->setRequest($request);
$response = $client->dispatch();

Setting GET parameters

Adding GET parameters to an HTTP request is quite simple, and can be done either by specifying them as part of the URL, or by using the setParameterGet() method. This method takes the GET parameters as an associative array of name => value GET variables.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
use Zend\Http\Client;
$client = new Client();

// This is equivalent to setting a URL in the Client's constructor:
$client->setUri('http://example.com/index.php?knight=lancelot');

// Adding several parameters with one call
$client->setParameterGet(array(
   'first_name'  => 'Bender',
   'middle_name' => 'Bending',
   'last_name'   => 'Rodríguez',
   'made_in'     => 'Mexico',
));

Setting POST Parameters

While GET parameters can be sent with every request method, POST parameters are only sent in the body of POST requests. Adding POST parameters to a request is very similar to adding GET parameters, and can be done with the setParameterPost() method, which is identical to the setParameterGet() method in structure.

1
2
3
4
5
6
7
8
9
use Zend\Http\Client;
$client = new Client();

// Setting several POST parameters, one of them with several values
$client->setParameterPost(array(
    'language'  => 'es',
    'country'   => 'ar',
    'selection' => array(45, 32, 80)
));

Note that when sending POST requests, you can set both GET and POST parameters. On the other hand, setting POST parameters on a non-POST request will not trigger an error, rendering it useless. Unless the request is a POST request, POST parameters are simply ignored.

A Complete Example

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
use Zend\Http\Request;
use Zend\Http\Client;
$request = new Request();
$request->setUri('http://www.test.com');
$request->setMethod('POST');
$request->getPost()->set('foo', 'bar');

$client = new Client();
$response = $client->dispatch($request);

if ($response->isSuccess()) {
    //  the POST was successful
}
[1]See RFC 2616 -http://www.w3.org/Protocols/rfc2616/rfc2616.html.

Table Of Contents

Previous topic

The Headers Class

Next topic

HTTP Client - Connection Adapters

This Page

Note: You need to stay logged into your GitHub account to contribute to the documentation.

Edit this document

Edit this document

The source code of this file is hosted on GitHub. Everyone can update and fix errors in this document with few clicks - no downloads needed.

  1. Login with your GitHub account.
  2. Go to HTTP Client - Overview on GitHub.
  3. Edit file contents using GitHub's text editor in your web browser
  4. Fill in the Commit message text box at the end of the page telling why you did the changes. Press Propose file change button next to it when done.
  5. On Send a pull request page you don't need to fill in text anymore. Just press Send pull request button.
  6. Your changes are now queued for review under project's Pull requests tab on GitHub.