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
// 将参数值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) . '"'
);