尽管在 return 中获得状态代码 200,但为什么 PHP cURL PUT 请求不起作用?

Why is PHP cURL PUT request not working despite getting status code 200 in return?

我被这个问题困扰了一段时间。我正在尝试使用 REST API 来更改用户的某些设置,例如清除用户并将他们的设备设置为非活动状态。

REST 调用是在 php 中进行的,我对此很陌生。大多数调用(get 和 post)工作正常,所以我想我理解 php 和 curl 的基本概念,但我就是无法让 put 请求正常工作。问题是,在进行 REST 调用时,我在 return 中得到一个状态代码 200,表明一切正常,但是当我检查数据库时,没有任何变化,设备仍然处于活动状态。

我在 stackexchange (, , 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'。尝试将您的 $data 编码为 json 然后传输 jsonEncodeteData:

$dataJson = json_encode($data);
curl_setopt($ch, CURLOPT_POSTFIELDS, $dataJson);

也许这已经有所帮助了。

status 200 在 PUT 请求的情况下可能不成功。在正确的语义(服务器的正确实现)中成功 PUT returns“201 Created”,如果客户端发送空内容或某种错误的内容,服务器 returns“204 No Content”。

懒惰的程序员可能只是 return“200 Ok”而不是 204,意思是 "your request is fine, but there is nothing to do with the data"。

尝试验证您的数据并确保您发送的内容不为空并且符合 API 规范。

据我所知,你的代码有两个问题。

  1. Content-Type: application/json 不正确,我会完全删除它。
  2. 您没有 Content-Length header.

我建议尝试

$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);