Search code examples
phpjoomla

How can I use HttpFactory in Joomla?


I used curl in Joomla,

curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/json',
        'X-API-KEY:' . $api_key,
        'X-SANDBOX:' . $sandbox,
));

but now I use HttpFactory for request to api:

$options = array(
    'Content-Type: application/json',
    'X-API-KEY:' . $api_key,
    'X-SANDBOX:' . $sandbox,
 );
 $answer = $this->http->post($url,json_encode($data,true),$options);

my result body is :

Unsupported request content type application/x-www-form-urlencoded"

why?


Solution

  • Your $options array has to be an associative array like the following:

    $options = array(
        'Content-Type' => 'application/json',
        'X-API-KEY' => $api_key,
        'X-SANDBOX' => $sandbox,
    );
    

    Short explanation: The 3rd parameter of the post() method in the Http class is expecting $headers information in a specific format:

    An array of name-value pairs to include in the header of the request.

    Link to Joomla Documentation

    You can get Joomla help from many experts at Joomla Stack Exchange: https://joomla.stackexchange.com/