HTTP Client

HTTP Client

Since version 8.2, Concrete CMS comes with an HTTP Client that can be used to perform requests to web sites. It can be used to send data, as well as to download files and other web resources.

Getting an HTTP Client instance

There are two kinds of clients. The first client kind uses the cURL PHP extension. To create an instance of it:

$client = $app->make('http/client/curl');

The cURL client is really reliable and powerful, but it's available only if the cURL PHP extension is not installed. That's why you can use a second kind of client, which uses low-level socket connections. To create an instance of it:

$client = $app->make('http/client/socket');

If you don't mind knowing which client you will be using:

$client = $app->make('http/client');

Concrete will automatically create the HTTP Client that's most suitable for your environment.

You can also get a new instance of an HTTP Client in your class constructors using the Dependency Injection provided by Laravel.

For instance, if may write your class as:

<?php

namespace MyNamespace;

use Concrete\Core\Http\Client\Client;

class MyClass
{
    /**
     * The HTTP Client instance.
     *
     * @var Client
     */
    protected $client;

    /*
     * Initializes the instance.
     *
     * @param Client $client
     */
    public function __construct(Client $client)
    {
        $this->client = $client;
    }
}

To initialize your class by automaticaly filling in its dependencies:

$myClassInstance = $app->make(\MyNamespace\MyClass::class);

The class constructor will receive automatically a new HTTP Client instance.

HTTP Client configuration

The default HTTP Client configuration is stored in the app.http_client.… configuration keys. You can find these keys, as well as a description of them, in the /concrete/config/app.php file (here's a link to it for Concrete version 8.2.0).

For instance, the connection timeout is represented by the app.http_client.connecttimeout configuration key.

If you want to customize the default configuration for every HTTP Client instance created, you can for instance use the c5:config CLI command. Here's how to increase the connection timeout to 10 seconds:

concrete/bin/concrete5 c5:config set -g app.http_client.connecttimeout 10

If you instead want to configure just a specific client instance, overriding the default configuration:

$client->setOptions([
    'connecttimeout' => 10,
]);

This approach uses the same keys used in the configuration files, without the leading app.http_client. part. You can also specify more that one option at once:

$client->setOptions([
    'connecttimeout' => 10,
    'maxredirects' => 1,
]);

Using the HTTP Client

The Concrete HTTP Client is a wrapper aroud the Zend HTTP Client. So, in order to use it, you can refer to its manual.