3

I am calling third party API using below methods:

$ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $this->_url . 'api/v1/ShipTos');
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json", "Authorization: Bearer $session", "Content-Length: " . strlen($data_string)));

        $out = curl_exec($ch);

How to call curl method in Magento 2 with example please?

10
 protected $curlClient;  

in construct add this

  public function __construct(     
        \Magento\Framework\HTTP\Client\Curl $curl

    ) {
        $this->curlClient = $curl;
    }

You can use this like

$this->curlClient->post($serviceUrl, []);
//response will contain the output in form of JSON string
$response = $this->curlClient->getBody();

For more option you can see this file, vendor\magento\framework\HTTP\Client\Curl.php

like

getBody()

addHeader()

setCredentials()

addCookie()

get() // for get request

makeRequest() // for make request

setOption() // set curl options

| improve this answer | |
  • Thanks Keyur, I have check in my code and come back any issues – Rama Chandran M Jun 8 '17 at 13:04
  • 1
    Sure Keyur. any idea different between? Magento\Framework\HTTP\Adapter\Curl Magento\Framework\HTTP\Client\Curl – Rama Chandran M Jun 9 '17 at 7:40
  • @keyur Thanks for your answer. Can you please explain the answer in detail?How to set each curl parameter as in the question(CURLOPT_URL, CURLOPT_CUSTOMREQUEST etc). I have searched in this file(vendor\magento\framework\HTTP\Client\Curl.php) and tried the code. But getting error as Fatal error: Uncaught Error: Call to protected method Magento\Framework\HTTP\Client\Curl::curlOption() from context. Any idea on this?? – Vindhuja Jul 10 '18 at 5:32
  • @Vindhuja Setting a request method is not possible. We need add the functionality in Curl class in next magento release. – Milind Singh Nov 30 '18 at 8:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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