繁体   English   中英

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

[英]How to format POST request using PHP curl methods?

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

$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":["此字段为必填项。"]}

我在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)]
);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM