Blog

Making external calls using HttpFactory

Usually when we want to make an external call we use cURL to make this call. Setting up the cURL instance is quite cumbersome and in general hard to remember all the things you need to setup. There are also servers that do not support cURL which means your code won't work. Building a fallback is required in those cases.

Using Joomla it is quite easy to setup cURL and any additional fallbacks, all you need is 1 line of code:

use Joomla\CMS\Http\HttpFactory;
use Joomla\Registry\Registry;
$options = new Registry; $http = HttpFactory::getHttp($options, ['curl', 'stream']);

This line returns a Joomla HTTP driver that allows you to make calls to outside URLs. The driver will use the transport drivers in the order as specified, so in this example cURL is first used if available, otherwise a stream will be used.

Joomla ships with 3 transport drivers:

  • cURL
  • socket
  • stream

These transport drivers are located in libraries/src/Joomla/Http/Transport/. In case you want to add your own transport drivers, they must be placed in this folder.

Making a call

To make a call to an external URL it is going to depend on what kind of call you want to make. Http supports the following calls:

  • delete
  • get
  • head
  • options
  • patch
  • post
  • put
  • trace

All these commands use the same argument set which is:

  1. URL
    The URL to call
  2. Data
    The data to send to the server
  3. Headers
    Any headers to send to the server. This can be used for authorization for example.
  4. Timeout
    Set a custom timeout to use

A post call to a url

$answer = $http->post($url);

A post call to a url with a payload

$answer = $http->post($url, ['foo' => 'bar']);

Processing the answer

The answer is always a HttpResponse object. This object has 3 properties:

  • code
    The HTTP response code
  • headers
    The response headers sent back by the server
  • body
    The response from the server

 

Related Articles