This is my curl code. How to write the same in Magento 2

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);

if($method == 'POST') {

curl_setopt($ch, CURLOPT_POSTFIELDS,$data);


curl_setopt($ch, CURLOPT_FOLLOWLOCATION ,1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Content-Type: application/json', 'Accept: application/json', 'Authorization:'.$key ));
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 120);
$result = curl_exec($ch);
return json_decode($result); 

Please help.


3 Answers 3

public function __construct(
    \Magento\Framework\HTTP\Client\Curl $curl,
    \Magento\Framework\Json\Helper\Data $jsonHelper
) {
    $this->curl = $curl;
    $this->jsonHelper = $jsonHelper;

$data = []; //add what you need if it is post
$this->curl->addHeader(); //add header
$this->curl->setOption(); //set required options
$this->curl->post(YOUR_URL_HERE, $data); // do post
$this->curl->get(YOUR_URL_HERE); // do get
$body = $this->curl->getBody();
if ($body) {
    $result = $this->jsonHelper->jsonDecode($body);

The below code is help to use curl in magento2.

$client = new \Zend_Http_Client();      
if($method == 'POST'){
$headers = ["Content-Type" => "application/json", "Accept" => "application/json",CURLOPT_RETURNTRANSFER => true, CURLOPT_FOLLOWLOCATION => 1,"Authorization" => $key,"CURLOPT_CONNECTTIMEOUT"=>120,"CURLOPT_SSL_VERIFYPEER"=>false];
$client->setHeaders($headers );
$response = $client->request($method)->getBody(); 

You will print the response by print_r($response);

  • can you provide an example without using new object. Jul 12, 2018 at 6:19

you can use the below code for cURL request

$apiUrl = "https://magento.com/magento-connect/platinumpartners/list";
$this->getCurlClient->post($apiUrl, []);
            CURLOPT_REFERER => $this->getReferer()
$response = json_decode($this->getCurlClient->getBody(), true);

for details info, you can go through Magento Official Doc

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.