Read More
Read More
Menu Close

    How To Use Curl In Magento 2

    How To Use Curl In Magento 2 -You are in right place if you want to use curl in magento style.i am going explain how you can use it.

    check the below code

    /**
     * @var \Magento\Framework\HTTP\Client\Curl
     */
    protected $_curl;
    
    /**
     * @param Context                             $context
     * @param \Magento\Framework\HTTP\Client\Curl $curl
     */
    public function __construct(
        Context $context,
        \Magento\Framework\HTTP\Client\Curl $curl
    ) {
        $this->_curl = $curl;
        parent::__construct($context);
    }
    
    public function execute()
    {
        //if the method is get
        $this->_curl->get($url);
        //if the method is post
        $this->_curl->post($url, $params);
        //response will contain the output in form of JSON string
        $response = $this->_curl->getBody();
    }

    $url => contain the endpoint url.
    $params => it’s an array, if you want to attach extra parameters in url.
    $response => it will contain the output in json form.

    Hope so it will help you.

    Searching for an experienced
    Magento 2 Company ?
    Read More
    . . .
    Discuss on Helpdesk

    Leave a Comment

    Your email address will not be published. Required fields are marked*


    7 comments

  • Esha
    How to close the curl client?
    • ashutosh srivastava (Moderator)
      you don’t have to worry about it, in this line $this->_curl->post($url, $params); connection opens and closes within the function and the output is saved.
  • Deepak
    How can we use PUT method
    • ashutosh srivastava (Moderator)
      In this blog the class that is used can only be used to make post and get request to put request you need to use this class:
      Magento\Framework\HTTP\Adapter\Curl you can open this class and can check write method for making curl request, and read method to read the response.
  • Idham Choudry
    how to add CURLOPT_HTTPHEADER to the curl?
  • Back to Top