首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用PHP curl方法格式化POST请求?

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

Stack Overflow用户
提问于 2020-04-10 23:59:52
回答 1查看 27关注 0票数 1

我试图发送带有此有效负载的post请求:

代码语言:javascript
复制
$request_content = [
    "data" => [
        [
            "sku" => "0987",
            "price" => $price,
            "category" => "moveis",
            "brand" => "bartira",
            "zip_code" => "07400000",
            "affiliate" => "google-shopping"
        ]
    ]
];

因为这是一篇文章,所以我将CURLOPT_POST设置为true;

代码语言:javascript
复制
$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内容是:

代码语言:javascript
复制
{
"data": [
    {
        "sku": "0987",
        "price": "5.99",
        "category": "moveis",
        "brand": "bartira",
        "zip_code": "07400000",
        "affiliate": "google-shopping"
    }
]
}

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

{“数据”:“此字段是必需的。”}

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

EN

回答 1

Stack Overflow用户

发布于 2020-04-11 00:14:58

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

代码语言:javascript
复制
//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)]
);
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61150406

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档