0

Doing POST of JSON data using PHP curl. However, every time data is submitted, error message is displayed:

{ "result" : null, "error":"Invalid method", "id": default, "jsonrpc": "2.0"" }

Of course, my first step was to submit data via browser using Live HTTP Headers plugin, so I can see how raw data looks like:

{"jsonrpc":"2.0","method":"get","id":1,"params":["2145359"]}

So I use this code to format my data:

$post_info=json_encode(array("jsonrpc"=>"2.0","method"=>"get","id"=>1,"params"=>array("2145359")), JSON_UNESCAPED_SLASHES)

When I echo my PHP data, it looks identical:

{"jsonrpc":"2.0","method":"get","id":1,"params":["2145359"]}

Then I use this curl function to post data:

$ch=curl_init();
curl_setopt($ch, CURLOPT_URL, some_post_url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_info);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_MAXREDIRS, 10);
$result=curl_exec($ch);
curl_close($ch);
return $result;

...and "invalid method" error comes. Any suggestions?

8
  • What, specifically, is the invalid method in the error? Commented Jan 19, 2017 at 22:53
  • I have no idea, this is the complete messages that comes from remote server Commented Jan 19, 2017 at 22:53
  • Magnus, thanks for your suggestion, it's good one. However, data is actually posted (browser posts data, and it works fine), not very sure why "get" is used inside post parameters. Commented Jan 19, 2017 at 23:00
  • Just tried not encoding and sending as array. A different error came - "error":"undefined method `values' for "Array":String" Commented Jan 19, 2017 at 23:17
  • Ah. Of course. Sorry, bad suggestion. Try using http_build_query() instead of json_encode. I forgot that CURL_OPTFIELDS needs a string, not an array. Commented Jan 19, 2017 at 23:26

1 Answer 1

1

Post the data as a "normal" post instead of a json string.

To convert an array into post data to be used with curl and CURLOPT_POSTFIELDS, you can use http_build_query() method.

Example:

$post_info = http_build_query(array(
    "jsonrpc" => "2.0",
    "method"  => "get",
    "id"      => 1,
    "params"  => array(
          "2145359"
    )
));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.