【问题标题】:Making Curl to PHP request json rpc使Curl到PHP请求json rpc
【发布时间】:2018-10-18 12:41:52
【问题描述】:

我正在尝试连接到 Electroneum 钱包 rpc。示例 Curl 请求是:-

 curl  -u user:pass --digest  -X POST http://127.0.0.1:8050/json_rpc  -d '{"jsonrpc":"2.0","id":"0","method":"'getaddress'","params":{}}'  -H 'Content-Type: application/json'

这在机器方面工作得很好。但是当我像这样尝试 PHP 时

 $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "http://127.0.0.1:8050/json_rpc");
    curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST);
    curl_setopt($ch, CURLOPT_USERPWD, "user" . ":" . "pass");
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, "{\"jsonrpc\":\"2.0\",\"id\":\"0\",\"method\":\"getaddress'\",\"params\":{}}'");
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: application/json'));
    curl_setopt($ch, CURLOPT_ENCODING, 'gzip,deflate');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    $response = curl_exec($ch);
    if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
    curl_close($ch);
  print_r($response);

它返回{ "error": { "code": -32601, "message": "Method not found" }, "id": "0", "jsonrpc": "2.0" }。我不知道为什么它不起作用,可能是由于--digest。需要帮助

【问题讨论】:

    标签: php json curl


    【解决方案1】:

    您忘记在请求选项中删除方法名称中的单引号:

    curl_setopt($ch, CURLOPT_POSTFIELDS, "{\"jsonrpc\":\"2.0\",\"id\":\"0\",\"method\":\"getaddress'\",\"params\":{}}'");
    

    应该是:

    curl_setopt($ch, CURLOPT_POSTFIELDS, "{\"jsonrpc\":\"2.0\",\"id\":\"0\",\"method\":\"getaddress\",\"params\":{}}'");
    

    但无论如何,如果您打算对他们的 JSON-RPC API 进行多次不同的调用,我建议您使用为您完成所有 JSON-RPC 协议处理的客户端库,例如 jsonrpc/jsonrpc

    【讨论】:

    • 哦,我明白了,谢谢你的帮助 :)
    • 如果它对您有帮助,请不要忘记验证答案,以供将来可能遇到相同问题的其他人使用;)
    【解决方案2】:

    实际上应该删除第 6 行中的 2 个单引号:

    curl_setopt($ch, CURLOPT_POSTFIELDS, "{\"jsonrpc\":\"2.0\",\"id\":\"0\",\"method\":\"getaddress'\",\"params\":{}}'");
    

    应该是:

    curl_setopt($ch, CURLOPT_POSTFIELDS, "{\"jsonrpc\":\"2.0\",\"id\":\"0\",\"method\":\"getaddress\",\"params\":{}}");
    

    请注意,在https://cloudflare-eth.com 等某些网关上,参数列表应使用方括号而不是大括号:

    curl_setopt($ch, CURLOPT_POSTFIELDS, "{\"jsonrpc\":\"2.0\",\"id\":\"0\",\"method\":\"getaddress\",\"params\":[]}");
    

    【讨论】:

      猜你喜欢
      • 2012-07-29
      • 1970-01-01
      • 1970-01-01
      • 2020-09-07
      • 1970-01-01
      • 2012-10-02
      • 2023-01-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多