2

In magento 1 you can make get request like this: First Authorizing object-

public function authorize($url)
{
    $cookie = $this->getCookieDir();
    $user = $this->getApiUser();
    $curl = curl_init($url);

    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_USERAGENT, '.....-API-client/1.0');
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($user));
    curl_setopt($curl, CURLOPT_HEADER, false);
    curl_setopt($curl, CURLOPT_COOKIEFILE, $cookie);
    curl_setopt($curl, CURLOPT_COOKIEJAR, $cookie);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);

    $response = curl_exec($curl);

    curl_close($curl);
    return $response;
}

Then

public function get($url)
{
    $cookie = $this->getCookieDir();
    $curl = $this->initCh($url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_USERAGENT, '.......-API-client/1.0');
    curl_setopt($curl, CURLOPT_HEADER, false);
    curl_setopt($curl, CURLOPT_COOKIEFILE, $cookie);
    curl_setopt($curl, CURLOPT_COOKIEJAR, $cookie);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);

    $out = curl_exec($curl); # Initiate a request to the API and stores the response to variable
    $code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
    curl_close($curl);
    return $out;
}

Now in Magento 2

\Magento\Framework\HTTP\Client\Curl::get($uri); calls makeRequest();

In makeRequest(); curl_init() is called and all curlOption() are set. So there shouldn't be anymore need to do like in Magento 1? If so how this is how it should be done? -

/**
 * @param $url
 * @return void
 */
public function doGet($url){
    $user = $this->getApiUser();
    $this->_curl->setHeaders(CURLOPT_POSTFIELDS, http_build_query($user));
   //setting everything else
    $this->_curl->get($url);
}

1 Answer 1

1

You can try below code to send cURL request in Magento 2.

public function __construct(
    \Magento\Framework\HTTP\Adapter\Curl $curl
   ) {
    $this->curl = $curl;
}
public function sendCurlRequest($dataToBeSend) {
   $body = json_encode($dataToBeSend);
   $headers = [
        'Content-Type: application/json',
        'Content-Length: ' . strlen($body)
  ];
  $this->curl->write('POST', $url, $http_ver = '1.1', $headers, $body);
  //For Get Request
  $this->curl->write('GET', $url);
  $response = $this->curl->read();
}

Let me know in case you need further assistance.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.