如何使用PHP curl方法格式化POST请求



我正在尝试发送一个带有以下负载的post请求:

$request_content = [
"data" => [
[
"sku" => "0987",
"price" => $price,
"category" => "moveis",
"brand" => "bartira",
"zip_code" => "07400000",
"affiliate" => "google-shopping"
]
]
];

由于这是一个帖子,我将CURLOPT_POST设置为true;

$encoded_request = json_encode($request_content);
$ch = curl_init("https://my-service/endpoint/");
curl_setopt($ch, CURLOPT_HTTPHEADER, ["Authorization: Token my-token"]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $encoded_request);

print_r中显示的$encoded_request内容为:

{
"data": [
{
"sku": "0987",
"price": "5.99",
"category": "moveis",
"brand": "bartira",
"zip_code": "07400000",
"affiliate": "google-shopping"
}
]
}

如果我在Postman上使用这些内容,我会从我请求的服务中得到正确的响应,但在我的代码中我得到了错误;

{"data":["This field is required."]}

curl_上缺少哪种配置来正确格式化有效负载?

您可以尝试设置CURLOPT_HTTPHEADER并更改变量$request_content,如下所示:

//set your data
$request_content = [
"data" => [
[
"sku" => "0987",
"price" => $price,
"category" => "moveis",
"brand" => "bartira",
"zip_code" => "07400000",
"affiliate" => "google-shopping"
]
]
];
$encoded_request = json_encode($request_content);
$ch = curl_init("https://my-service/endpoint/");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $encoded_request);
// Set HTTP Header for POST request 
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Authorization: Token my-token',
'Content-Type: application/json',
'Content-Length: ' . strlen($encoded_request)]
);

最新更新