To make an HTTP request in Magento 2, you can use the following steps:
First, you need to inject the HTTP client class into your class using dependency injection. You can do this by adding the following line of code in your class constructor:
public function __construct(
\Magento\Framework\HTTP\Client\Curl $curl
) {
$this->curl = $curl;
}
Now you can use the $this->curl
object to make an HTTP request. You can set the request method, headers, and body using the following methods:
// Set the request method
$this->curl->setOption(CURLOPT_CUSTOMREQUEST, 'POST');
// Set the request headers
$this->curl->setHeaders(['Content-Type: application/json']);
// Set the request body
$this->curl->setBody(json_encode($requestBody));
Finally, you can send the request and get the response using the following code:
// Send the request
$this->curl->get($url);
// Get the response status code
$statusCode = $this->curl->getStatus();
// Get the response body
$responseBody = $this->curl->getBody();
That’s it! You have now made an HTTP request in Magento 2 using the Curl client class.