HTTP client

As of Totara 13, Totara core provides an object-oriented HTTP client wrapper for making external requests.

The code is located in the following server/totara/core/classes/http/ folder.

In the example below the class is making use of the existing curl class defined in server/lib/filelib.php so will automatically make use of any proxy defined in Quick-access menu > Server > HTTP > Web proxy.

The class allows you to work with client/request/response objects in an object-oriented way:

use totara_core\http\clients\curl_client;
use totara_core\http\request;
use totara_core\http\method;

$client = new curl_client();

$request = new request($url, method::POST, $postdata, $headers);
// Alternative syntax:
// $request = request::post($url, $postdata, $headers);

$response = $client->execute($request);

// Example methods available on response object:
$true_or_false = $response->is_ok();
$json = $response->get_body_as_json();
$status_code = $response->get_http_code;
$headers = $response->get_response_headers();
$specific_header = $response->get_response_header('header_name_as_string');

Clients can be extended to add use-case-specific functionality. The library also provides mock clients for testing in the /server/totara/core/classes/http/clients/ folder.