用PHP curl获取jsonRPC数据。

问题描述 投票:0回答:1

在我的vps上设置一个JSON-RPC,我想通过PHP CURL连接到我的网站上,做一个基本的请求,寻找getmasternodecount。

之前尝试了很多脚本和库,但似乎都不适合我的情况。现在我试着写一些基本的php代码,但这个技能不是我最好的。

<?php

error_reporting(E_ALL);
ini_set('display_errors', '1');

function coinFunction () {

    $feed = 'http://user:pass@ip/';
    $post_string = '{"method": "getmasternodecount", "params": []}';

    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, $feed);
    curl_setopt($ch, CURLOPT_PORT, port);
    curl_setopt($ch, CURLOPT_USERPWD, "user:pass");
    curl_setopt($ch, CURLOPT_HEADER, 1); 
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_VERBOSE, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string);
    //curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: application/stratum', 'Content-length: '.strlen($post_string)));
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: application/json', 'Content-length: '.strlen($post_string)));

    $output = curl_exec($ch);
    curl_close($ch);



    return $output;


}

$data = coinFunction();
var_dump($data);

echo $data;

?>

并给我这个数据转储:字符串(127) "HTTP1.1 403禁止日期。Sun, 24 May 2020 00:06:21 GMT Content-Length: 0 Content-Type: texthtml; charset=ISO-8859-1 " HTTP1.1 403 Forbidden Date: Sun, 24 May 2020 00:06:21 GMT Content-Length: 0 Content-Type: texthtml; charset=ISO-8859-1

当我删除所有的var dump信息等时,它给我发了一个白页,有时是NULL。

敬请关注。

php curl json-rpc
1个回答
1
投票

让我们从第一个片段开始工作。由于它是一个POST请求。file_get_contents 在这里相当不合适。添加以下 setopt 行。

curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_HEADER, 0);

如果没有这些,结果是 curl_exec 不会包含返回的内容。

另外,最好是指定 Content-Type 的请求(即 application/json). 即使没有,服务器也可能会处理,但以防万一。

curl_setopt($curl, CURLOPT_HTTPHEADER, array(
    'Content-Type:application/json'));

认证是另一回事。URL中的凭证建议使用Basic,但服务器可能会认为不是这样...... 请看 CURLOPT_HTTPAUTH.

© www.soinside.com 2019 - 2024. All rights reserved.