我正在尝试连接到基于 JSON-RPC 2.0 的 API。因为我是新手,所以我不确定我是否正确编码,因为我收到的只是一个错误。
谁能给我简单解释一下如何在 PHP 中连接 API?
<?php
header('Content-Type: application/json');
//check if you have curl loaded
if(!function_exists("curl_init")) die("cURL extension is not installed");
$url = 'xxxxxxxxx';
$data = array(
"operator_id" => "xxxx",
"login" => "xxxx",
"password" => "xxxx",
);
$curl_options = array(
CURLOPT_URL => $url,
CURLOPT_HEADER => 0,
CURLOPT_NOBODY => true,
CURLOPT_POSTFIELDS => $data,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_TIMEOUT => 0,
CURLOPT_SSL_VERIFYPEER => 0,
CURLOPT_FOLLOWLOCATION => TRUE,
CURLOPT_ENCODING => 'gzip,deflate',
CURLINFO_HEADER_OUT => true,
);
$ch = curl_init();
curl_setopt_array($ch, $curl_options);
$output = curl_exec($ch);
curl_close($ch);
$arr = json_decode($output,true);
echo ($output);
?>
Run Code Online (Sandbox Code Playgroud)
我收到的响应是这样的: {"jsonrpc":"2.0","error":{"code":-32600,"message":"无效请求"},"id":null}
如果成功登录,我应该收到的响应是: {"jsonrpc":"2.0","result":true,"error":null,"id":1,"ts":1368533487}
您根本没有发送 JSON-RPC 请求。
请求必须是 JSON 正文,因此您必须先对数据进行 json_encode,然后再将其传递到 CURLOPT_POSTFIELDS。
发布的 json 必须具有键method
、params
、id
和jsonrpc
(最后一个应设置为“2.0”)。您的数据将进入params
. 可以id
设置为任何值,但如果没有它,您根本不会得到响应。
这是一种非常简单的格式。请参阅http://www.jsonrpc.org/specation上的规范