我已经被这个问题困扰了一段时间了。我正在尝试使用REST API更改用户的某些设置,例如清除用户并将其设备设置为非活动状态。
REST调用是用php进行的,这是我的新手。大多数调用(获取和发布)都工作正常,所以我想我了解php和curl的基本概念,但我无法使put请求工作。问题是,在进行REST调用时,我得到的状态码为200,表示一切正常,但是当我检查数据库时,没有任何更改,并且设备仍处于活动状态。
我已经花了几个小时在stackexchange(cURL PUT Request Not Working with PHP,Php Curl return 200 but not posting,PHP CURL PUT function not working)上研究此问题,并另外阅读了各种教程。 对我来说,我的代码看起来不错,并且非常合理,类似于我在网上找到的许多示例。因此,请帮助我找到我的错误。
$sn = "123456789";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://example.com/api/sn/".$sn);
$data = array("cmd" => "clearUser");
$headers = array(
'Accept: application/json',
'Content-Type: application/json'
);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$username = 'XXX';
$password = 'XXX';
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS,http_build_query($data));
$output = curl_exec($ch);
curl_close($ch);
答案 0 :(得分:0)
您在标题“ Content-Type:应用程序/ json”中定义。尝试将$ data编码为json,然后传输jsonEncodeteData:
$dataJson = json_encode($data);
curl_setopt($ch, CURLOPT_POSTFIELDS, $dataJson);
也许这已经有所帮助。
答案 1 :(得分:0)
懒惰的程序员可能只是返回“ 200 Ok”而不是204,意思是“您的请求很好,但是与数据无关”。
尝试验证您的数据,并确保发送的内容不为空且符合API规范。
答案 2 :(得分:0)
据我所知,您的代码中有两个问题。
Content-Type: application/json
不正确,我将其完全删除。Content-Length
标头。我建议尝试
$sn = "123456789";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://example.com/api/sn/".$sn);
$data = array("cmd" => "clearUser");
$httpQuery = http_build_query($data);
$headers = array(
'Accept: application/json',
'Content-Length: ' . strlen($httpQuery)
);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$username = 'XXX';
$password = 'XXX';
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS,$httpQuery);
$output = curl_exec($ch);
curl_close($ch);