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; $http = HttpFactory::getHttp(null, ['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:
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:
All these commands use the same argument set which is:
The URL to call
The data to send to the server
Any headers to send to the server. This can be used for authorization for example.
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:
The HTTP response code
The response headers sent back by the server
The response from the server