PHP CURL 使用 POST 原始 JSON 数据

14

我正在使用 PHP curl 进行 post 请求,但由于某种原因,我无法成功提交表单。

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

如果你发送的是 text/plain,那么 $postData 应该是一个字符串而不是一个数组。 - Barmar
我建议您查看此答案 https://dev59.com/D2Yr5IYBdhLWcg3wi6s_#13596901,因为它也适用于您的情况。您应该从数组中构建post字符串,而不是传递一个数组。 - pzaj
在发送之前对$ postData进行Json编码。 - pokeybit
你确定API需要明文参数吗?大多数使用url编码或JSON。 - Barmar
你确定 content-type 是 text/plain 吗? - Dolly Aswin
显示剩余7条评论
2个回答

30
如果您想使用Content-type: application/jsonraw数据,那么您的数据应该是json格式。
$ch = curl_init();
$headers  = [
            'x-api-key: XXXXXX',
            'Content-Type: application/json'
        ];
$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);

1
块数组模式是解决方案的关键。 - Codedreamer
3
为什么你的回答是text/plain格式? - danronmoon
1
我发现头部需要是“Content-Type: application/json”,才能将请求的“原始”正文内容处理为JSON。 - Nathaniel Rogers

8

如果您想要一个排列和解释过的格式,请参见以下代码。

// Set The API URL
$url = 'http://www.example.com/api';

// Create a new cURL resource
$ch = curl_init($url);

// Setup request to send json via POST`
$payload = json_encode(array(
    'data1' => 'value1',
    'data2' => 'value2'
   )
);

// Attach encoded JSON string to the POST fields
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);

// Set the content type to application/json
curl_setopt($ch, CURLOPT_HTTPHEADER, array('x-api-key: XXXXXX', 'Content-Type: application/json'));

// Return response instead of outputting
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// Execute the POST request
$result = curl_exec($ch);

// Get the POST request header status
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);

// If header status is not Created or not OK, return error message
if ( $status !== 201 || $status !== 200 ) {
   die("Error: call to URL $url failed with status $status, response $result, curl_error " . curl_error($ch) . ", curl_errno " . curl_errno($ch));
}

// Close cURL resource
curl_close($ch);

// if you need to process the response from the API further
$response = json_decode($result, true);

我希望这能对某人有所帮助


2
检查状态应该是 if (!$status || !($status == 201 || $status == 200)) { - Nick Weavers
聪明的观察 @NickWeavers - nensamuel
为什么两个答案都将Content-Type头设置为text/plain? - danronmoon
@danronmoon 感谢您的观察,我已经更新它以反映“application/json”。 - nensamuel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接