0

我正在摆弄一个免费的 API,一切都很好,但偶尔会出现以下错误。

Fatal error: Uncaught exception 'Exception' with message 'Invalid data received, please make sure connection is working and requested API exists' in /MY SERVER PATH/functions.php:39 Stack trace: #0 /MY SERVER PATH/index.php(5): myFunc('getInfo') #1 {main} thrown in /MY SERVER PATH/functions.php on line 39

我只是好奇为什么会这样?

以下是相关代码供参考。

感谢大家的额外帮助。


来自 FUNCTIONS.PHP 的片段

function myFunc($method, array $req = array()) {
    // API settings
    $key = 'MY API KEY'; // your API-key
    $secret = 'MY SECRET'; // your Secret-key

    $req['method'] = $method;
    $mt = explode(' ', microtime());
    $req['nonce'] = $mt[1];

    // generate the POST data string
    $post_data = http_build_query($req, '', '&');

    $sign = hash_hmac("sha512", $post_data, $secret);

    // generate the extra headers
    $headers = array(
            'Sign: '.$sign,
            'Key: '.$key,
    );

    // our curl handle (initialize if required)
    static $ch = null;
    if (is_null($ch)) {
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; PHP client; '.php_uname('s').'; PHP/'.phpversion().')');
    }
    curl_setopt($ch, CURLOPT_URL, 'URL TO THE API');
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);

    // run the query
    $res = curl_exec($ch);
    if ($res === false) throw new Exception('Could not get reply: '.curl_error($ch));
    $dec = json_decode($res, true);
    if (!$dec) throw new Exception('Invalid data received, please make sure connection is working and requested API exists');
    if (!$dec){
        echo '';
    }else{
    return $dec;
    }

}

来自 INDEX.PHP 的片段

$result = myFunc("getInfo");
4

1 回答 1

0

问题就在这里

$dec = json_decode($res, true);
if (!$dec) throw new Exception('Invalid data received, please make sure connection is working and requested API exists');

!$dec此处不正确,因为服务器可以使用false, null,等进行响应,这0很可能是有效的响应,但是您的代码会将这些错误视为 json_decoding 的错误。要使用 json_decode 检查错误,请改用 json_last_error。

$dec = json_decode($res, true);
$err = json_last_error();
if ($err !== JSON_ERROR_NONE) throw new Exception('Invalid data received, please make sure connection is working and requested API exists');
于 2013-05-12T19:39:00.103 回答