以前我使用XML方式从外部API获取数据。现在,内部公司策略命令使用JSON与API通信。我知道我应该在请求中发送什么数据以及我将如何获取数据,但我不知道如何使用JSON调用API。
我找到了示例,但我不知道什么是 Http_client(),它的角色是什么以及它将做什么。
$http = new Http_Client();
$http->setUri('https://api.example.com/service-api');
$postdata = array(
'action' => 'authorization',
'args' => array(
'username' => 'firstname@dev.com',
'password' => 'qpujy676',
)
);
if (CRYPT_KEY_API) { //if encrypted data
$postdata ['rand'] = md5(time() . rand(2303, 85500));
$postdata = json_encode($postdata);
$postdata = Crypt::encrypt($postdata);
} else {
$postdata = json_encode($postdata);
}
$http->setRawData($postdata, 'application/json');
$response = $http->request(POST);
if ($response->isSuccessful()) {
$responseData = $response->getBody();
if (CRYPT_KEY_API) { //if encrypted data
$responseData = Crypt::decrypt($responseData);
}
$results = json_decode($responseData, true);
} else {
$error_message = "<p>Error</p>\n";
$error_message .= "HTTP Status: " . $response->getStatus() . "\n";
$error_message .= "HTTP Headers:\n";
$responseHeaders = $response->getHeaders();
foreach ($responseHeaders as $responseHeaderName => $responseHeaderValue) {
$error_message .= "$responseHeaderName: $responseHeaderValue\n";
}
throw new Exception($error_message);
}
实际上我只需要示范 http_client 类来解决我的问题:-)特别是
我创建了方法autorization_test(),据说应该使用外部API进行响应。据说,因为它的输出是:
警告: 的file_get_contents(https://api.example.com/service-api): 无法打开流:HTTP请求失败!找不到HTTP / 1.1 404 第180行的C:\ xampp \ htdocs \ prestashop1611 \ modules \ miniwa \ miniwa.php 错误
public function authorization_test()
{
$domain = MINIWA_DOMAIN;
$username = 'tester@user.com';
$password = '12345';
$postData = array(
'action' => 'authorization',
'args' => array(
'domain' => $domain,
'username' => $username,
'password' => $password,
),
);
$postData = json_encode($postData);
//$postData = Crypt::encrypt($postData);
$context = stream_context_create(array(
'http' => array(
// http://www.php.net/manual/en/context.http.php
'method' => 'POST',
'header' => 'Content-Type: application/json',
'content' => $postData,
)
));
// Send the request
$response = file_get_contents('https://api.example.com/service-api', FALSE, $context);
// Check for errors
if($response === FALSE){
die('Error');
}
//$response= Crypt::decrypt($response);
// Decode the response
$responseData = json_decode($response, TRUE);
// send the output data to view
$smarty->assign(array(
'json_decoded_output' => $responseData,
));
return $smarty;
为什么没有正输出?
答案 0 :(得分:1)
答案 1 :(得分:0)
API被禁用,现在没问题,代码是正确的。