4

Currently i'm using magento 2 curl framework to connect to rest api like this:

public function __construct(\Magento\Framework\HTTP\Client\Curl $curl
  ) {
      $this->_curl = $curl; 
  }

private function post(){
      $url = "https://pro.test.com/api/test";
      $params = array("invoice"=>"SOCAG00183235715","method"=>"ups");
      $this->_curl->post($url, $params);
      $response = $this->_curl->getBody();
      return json_decode($response);
  }

from the above code, i can add parameter to the post field, the problem is i need to add the array option to curl header, for example if i use basic curl php, the code structure will look like this:

$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => "https://pro.test.com/api/test",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => "invoice=SOCAG00183235715&method=ups",
  CURLOPT_HTTPHEADER => array(
    "content-type: application/x-www-form-urlencoded",
    "key: 212thisismykey6969"
  ),
));

$response = curl_exec($curl);
$err = curl_error($curl);
0
$headers = ["Content-Type" => "application/x-www-form-urlencoded", 
"key" => "212thisismykey6969"];
$this->_curl->setOption(CURLOPT_RETURNTRANSFER, true);
$this->_curl->setHeaders($headers);
$this->_curl->post($url,$params);
$response = $this->_curl->getBody();

 

For Reference :- check the below link

https://devdocs.magento.com/guides/v2.4/get-started/gs-curl.html

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.