PHP JSON 使用基本身份验证时出错

PHP JSON Error when using Basic Authentication

我是 PHP 的新手,我正在尝试通过基本身份验证发送 JSON 请求。服务器响应此错误:

 object(stdClass)#1 (2) { ["error"]=> object(stdClass)#2 (2) {  
 ["code"]=> int(-32600) ["message"]=> string(44) "expected content type 
 to be application/json" } ["jsonrpc"]=> string(3) "2.0" } 

来自 API 文档,这里是请求格式:

  Request Format:

  {
      "jsonrpc": "2.0",
       "id":1,
       "method": "acct.name.get",
       "params": [
             "QrOxxEE9-fATtgAD" ]
  }

这是代码...任何帮助都会很棒 - 谢谢

 <?php

 $username = "username";
 $password = "password";

 $request = [
    'jsonrpc' => '2.0',
    'id' => 1,
    'method' => 'acct.name.get',
    'params' =>['CA6ph0n7EicnDADS'],
 ];

 $curl_post_data = json_encode($request);

 $service_url = 'https://userapi.voicestar.com/api/jsonrpc/1';
 $curl = curl_init($service_url);
 curl_setopt($curl, CURLOPT_URL, $service_url);
 curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
 curl_setopt($curl, CURLOPT_USERPWD,  "username:password");
 curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
 curl_setopt($curl, CURLOPT_POST, true);
 curl_setopt($curl, CURLOPT_POSTFIELDS, $curl_post_data);
 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
 $curl_response = curl_exec($curl);
 $response = json_decode($curl_response);
 curl_close($curl);

 var_dump($response);

?>

在我看来 API 正在寻找请求 header 以反映 JSON。

尝试将以下内容添加到您的选项中并查看返回的内容

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

实际上,这是小事...您的 JSON/Array 格式不正确。 params 末尾的额外逗号实际上可能是问题所在。尝试以下操作。

格式不正确的数组将导致 json_encode 到 return 为 null。

 <?php

 $username = "username";
 $password = "password";

 $request = [
    'jsonrpc' => '2.0',
    'id'      => 1,
    'method'  => 'acct.name.get',
    'params'  => ['CA6ph0n7EicnDADS']
 ];

 $curl_post_data = json_encode($request);

 $headers = ['Content-type: application/json'];


 $service_url = 'https://userapi.voicestar.com/api/jsonrpc/1';
 $curl = curl_init($service_url);
 curl_setopt($curl, CURLOPT_URL, $service_url);
 curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
 curl_setopt($curl, CURLOPT_USERPWD,  "username:password");
 curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
 curl_setopt($curl, CURLOPT_POST, true);
 curl_setopt($curl, CURLOPT_POSTFIELDS, $curl_post_data);
 curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
 $curl_response = curl_exec($curl);
 $response = json_decode($curl_response);
 curl_close($curl);

 var_dump($response);

?>