浏览文章
文章信息
Magento2 使用curl访问rest api接口实例|Magento2 use curl connect to REST Api exsample
17780
怎么在Magento2中使用curl访问接口?
/** * @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() { //get访问方式 $this->_curl->get($url); //post访问方式 $this->_curl->post($url, $params); //响应将包含JSON字符串形式的输出 $response = $this->_curl->getBody(); }实例:
$url="http://localhost/magento2/index.php/"; $token_url=$url."rest/V1/integration/admin/token"; $product_url=$url. "rest/V1/products"; $username="admin"; $password="admin@123"; //Authentication rest API magento2, get access token $ch = curl_init(); $data = array("username" => $username, "password" => $password); $data_string = json_encode($data); $ch = curl_init($token_url); 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', 'Content-Length: ' . strlen($data_string)) ); $token = curl_exec($ch); $ch = curl_init("http://localhost/magento2/index.php/rest/V1/orders/1"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json", "Authorization: Bearer " . json_decode($token))); $result = curl_exec($ch); $result = json_decode($result, 1); echo '<pre>';print_r($result);