Zend\Http

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.

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 seperated 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
use Zend\Http\Client;
use Zend\Http\Request;

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

// 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.
blog comments powered by Disqus