PHP通过CURL请求restAPI出错,如何解决?

PHP通过CURL请求restAPI出错


      $runCommand = array('sun at 13:16', 'Full 1st Sat at 21:00');
      //创建客户端
      $data = array(
          'name' => 's050 901',
          'description' => 'description  111111',
          'enabled' => 'yes',
          'runCommand' => $runCommand
      );
   $result_create=$this->getCommonModel()->createSchedule($data);

请求方法:

   public function createSchedule($data){
        //获取token
        $token=$this->getAuthToken();

        //获取配置信息
        $rest_config = $this->getServiceLocator()->get('ModuleManager')->getModule('Common')->getConfig();
        $restinfo=$rest_config['rest_api'];

        $ch = curl_init();
        // 设置Bareos REST API的URL
        curl_setopt($ch, CURLOPT_URL, $restinfo['rest_url'].'/configuration/schedules');
        // 设置要提交的数据

        $data = json_encode($data);

        // 设置CURL选项
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json',
            'Content-Length: ' . strlen($data),
            'Authorization: Bearer ' . $token
        ));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

        // 发送请求并获取响应
        $response = curl_exec($ch);

        // 关闭CURL会话
        curl_close($ch);

        return $response;
    }

最终服务端生成的命令是\u0027configure add schedule name=s050901 description=description111111 runCommand=sunat13:16,Full1stSatat21:00 enabled=yes\u0027

正确的应该是\u0027configure add schedule name=s050901 description=description111111 runCommand="sun at 13:16,Full 1st Satat 21:00" enabled=yes\u0027
而且name跟description这两个参数值里面的空格也丢了
上面的代码哪里出了问题,chatgpt别来凑热闹,必举报

你先本地把值打印出来看看,排查是客户端代码问题,还是服务端代码问题

$runCommand = array('"sun at 13:16"', '"Full 1st Sat at 21:00"');

该回答引用ChatGPT
问题是调用REST API时,请求中的参数值因为空格等问题导致生成的命令不正确。这是因为在发送POST请求前将参数转化为json时,没有对参数值进行处理。

解决方案可以是在转化为json前,针对参数值进行urlencode()处理,将空格转化为%20等特殊字符。代码修改如下:


// 将参数值urlencode()处理
foreach ($data as $key => $value) {
$data[$key] = urlencode($value);
}
$data = json_encode($data);


另外,在生成命令时需要将参数值中的逗号等特殊字符用引号包裹起来,可以在相应位置加上双引号即可。


$runCommand = array('sun at 13:16', 'Full 1st Sat at 21:00');
$data = array(
'name' => 's050 901',
'description' => 'description 111111',
'enabled' => 'yes',
'runCommand' => '"' . implode(',', $runCommand) . '"'
);


这样就可以解决参数值中空格等特殊字符引起的命令错误问题了。