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

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

我正在尝试使用此有效负载发送发布请求:

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

$encoded_request
中显示的
print_r
内容为:

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

如果我在

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

{"data":["此字段为必填项。"]}

为了正确格式化有效负载,我在

curl_
上缺少哪种配置?

php php-curl
1个回答
1
投票

您可以尝试设置 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)]
);
© www.soinside.com 2019 - 2024. All rights reserved.