我在Magento 2中从外部API获取响应时遇到问题。我的参数未在json中正确编码。我正在使用Magento \ Framework \ HTTP \ ZendClientFactory来访问它。
下面是我尝试调用api并获取响应的代码,我不确定哪里出问题了。
public function apiCaller()
{
$apiKey = $this->getConfigData('bearer_token');
$endpointUrl = $this->getConfigData('session_endpoint');
$params = array(
"origin" => "Kandy",
"destination" => "Nugegoda",
"weight" => "1.0",
"domestic" => "true"
);
$json = json_encode($params);
$client = $this->_httpClientFactory->create();
$client->setUri($endpointUrl);
$client->setMethod(\Zend_Http_Client::POST);
$client->setHeaders(\Zend_Http_Client::CONTENT_TYPE, self::$jsonDataType);
$client->setHeaders('API-KEY', $apiKey);
$client->setParameterPost($json);
$request = $client->request();
$response = $request->getBody();
$this->_logger->log(100, print_r(json_decode($response),true));
$this->_logger->log(100, print_r($params,true));
return $response;
}
下图显示了预期的结果:
实际结果在我的调试日志文件中:
[2019-01-04 07:12:06] main.DEBUG:stdClass对象 ( [来源] =>是必需的 )