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

时间:2016-02-25 01:06:28

标签: php json 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);

?>

2 个答案:

答案 0 :(得分:1)

实际上,它是小事......你的JSON / Array格式不正确。在params结束时额外的逗号可能实际上是问题。尝试以下方法。

格式错误的数组会导致json_encode返回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);

?>

答案 1 :(得分:0)

在我看来,API正在寻找反映JSON的请求标头。

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

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