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?

12

1 Answer 1

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

4
  • Thanks Keyur, I have check in my code and come back any issues Jun 8, 2017 at 13:04
  • 1
    Sure Keyur. any idea different between? Magento\Framework\HTTP\Adapter\Curl Magento\Framework\HTTP\Client\Curl Jun 9, 2017 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, 2018 at 5:32
  • @Vindhuja Setting a request method is not possible. We need add the functionality in Curl class in next magento release. Nov 30, 2018 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.