在PHP中使用参数调用JSON API(示例)


Call JSON API with params in PHP (with example)

以前使用XML方式从外部API获取数据。现在,公司内部政策要求使用JSON与API通信。我知道我应该在请求中发送什么数据,以及我将如何获得数据,但我不知道如何通过JSON调用API。

  • 我的PHP服务器是localhost
  • 让JSON API位于https://api.example.com/service-api,我确信它工作正常。
  • 请求{"行动":"授权","参数":{"用户名":"firstname@dev.com","密码":"qpujy676}}
  • 回调{"地位":"OK","令牌":"8 hsa77hh687y3sbdha7ah3dajknfa93"}

我找到了一个例子,但我不知道什么是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类来解决我的问题:-)特别是

  • setRawData (postdata美元,application/json)
  • 请求(POST)
  • getBody ()

我创建了autorization_test()方法,它应该响应外部API。假定,因为它的输出是:

警告:file_get_contents (https://api.example.com/service-api):打开流失败:HTTP请求失败!HTTP/1.1 404不存在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;

为什么没有正输出?

这里有完整的文档:https://pear.php.net/manual/en/package.http.http-client.http-client-summary.php

API被禁用,现在是OK的,代码是正确的