如何使用 cURL 发送带有 JSON 正文的 PUT 请求?

问题描述 投票:0回答:1

我有这个代码来发送 PUT 请求:

$curl = curl_init($url);
curl_setopt($curl, CURLOPT_PUT, true);
curl_setopt($curl, CURLOPT_BODY, json_encode($result));

curl_exec($curl);

但这不起作用,因为

CURLOPT_BODY
不存在。但是,如何将正文添加到我的
PUT
请求中?我尝试了
CURLOPT_POSTFIELDS
,但这将我的通话变成了
POST
(而且我确实需要
PUT
)。

php curl put
1个回答
0
投票

cURL 本身无法执行

PUT
请求。

您需要执行以下操作:

$curl = curl_init($url);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($result));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($curl);
© www.soinside.com 2019 - 2024. All rights reserved.