cURL (client URL) is used to call third-party API data on your website. As a good Magento developer, you should avoid PHP default cURL in your Magento 2 website. Magento provides a cURL class to transmit HTTP requests and receive responses from third-party services. The Magento class for cURL is Magento\Framework\HTTP\Client\Curl
Magento 2 cURL POST Example
<?php
namespace Dhairvi\Demo\Helper;
/**
* Class Data
*/
class Data extends \Magento\Framework\App\Helper\AbstractHelper
{
/**
* @var \Magento\Framework\HTTP\Client\Curl
*/
protected $curl;
/**
* @param \Magento\Framework\App\Helper\Context $context
* @param \Magento\Framework\HTTP\Client\Curl $curl
*/
public function __construct(
\Magento\Framework\App\Helper\Context $context,
\Magento\Framework\HTTP\Client\Curl $curl
) {
parent::__construct($context);
$this->curl = $curl;
}
public function postExample()
{
$header = ["Content-Type" => "application/json", "Content-Length" => "200"];
$this->curl->setHeaders($header);
$this->curl->setOption(CURLOPT_RETURNTRANSFER, true);
$this->curl->setOption(CURLOPT_PORT, 8080);
$this->curl->setOption(CURLOPT_TIMEOUT, 0);
$request = [
'data_1' => 'value_1',
'data_2' => 'value_2',
'data_3' => 'value_3',
'data_4' => 'value_4',
'data_5' => 'value_5',
];
$requestJsonData = json_encode($request);
$url = 'POST_URL';
$this->curl->post($url, $requestJsonData);
$result = $this->curl->getBody();
return $result;
}
}
Similar to the POST, you can implement GET; the following is a quick example of a GET request.
$this->curl->get($url); $result = $this->curl->getBody();

