【发布时间】:2019-08-06 15:13:55
【问题描述】:
我已经被这个问题困扰了一段时间了。我正在尝试使用 REST API 更改用户的某些设置,例如清除用户并将其设备设置为非活动状态。
REST 调用是在我很陌生的 php 中进行的。大多数调用(get 和 post)都工作得很好,所以我想我理解了 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);
【问题讨论】:
-
如果设置
Content-Type: application/json可能curl_setopt($ch, CURLOPT_POSTFIELDS,json_encode($data));