cURL request in Magento
cURL request in Magento
Most of the time there is a need to call 3rd party APIs from Magento.
We use cURL functions for the same, now here is an interesting part, Magento has wrapper functions for the same in its own library.
This make it easy for calling the 3rd party API url’s.
Code snippet is as shown below.
$param = array(); //initialise the request variable $param['userid'] = 'abc'; //username goes here $param['password'] = '123'; //password goes here $url = 'abc.com';//the API url goes here try { $http = new Varien_Http_Adapter_Curl(); $config = array('timeout' => 10); # timeout set to 10 seconds or whatever you like! //$config = array('timeout' => 10,'userpwd'=>'username:password'); //this is also a valid way to aunthenticate $http->setConfig($config); ## make a POST call $http->write(Zend_Http_Client::POST, $url, '1.1', array(), $param); //$http->write(Zend_Http_Client::POST, $url, '1.1', array('Content-Type: text/xml'),$xml); //here $xml is the request data in XML format ## Get Response $res = $http->read(); $cod = Zend_Http_Response::extractCode($res); $response = ''; if ($cod == 200) //if success { $tmp = preg_split('/^\r?$/m', $res, 2); $response = trim($tmp[1]); } # Close Call $http->close(); } catch (Exception $e) { Mage::logException($e); }