小编典典

PHP CURL使用POST原始JSON数据

json

我正在使用PHP curl进行发布,由于某种原因,我无法成功发布该表单。

$ch = curl_init();
$headers = [
            'x-api-key: XXXXXX',
            'Content-Type: text/plain'
        ];
$postData = array (
    'data1: value1',
    'data2: value2'
);
curl_setopt($ch, CURLOPT_URL,"XXXXXX");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);           
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

$server_output = curl_exec ($ch);

当我尝试在帖子中使用相同功能时,它可以工作,但不适用于PHP。

var_dump($server_output) ==> string(67) ""require data1 and data2 or check the post parameters""
var_dump(curl_error($ch)) ==> string(0) ""

阅读 284

收藏
2020-07-27

共1个答案

小编典典

如果您想使用Content-type: application/jsonraw数据,似乎您的数据应采用json格式

$ch = curl_init();
$headers  = [
            'x-api-key: XXXXXX',
            'Content-Type: text/plain'
        ];
$postData = [
    'data1' => 'value1',
    'data2' => 'value2'
];
curl_setopt($ch, CURLOPT_URL,"XXXXXX");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postData));           
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result     = curl_exec ($ch);
$statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
2020-07-27