簡體   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