我在使用 PHP 中的 curl_setopt 函数进行格式化时遇到了问题。我基本上是在尝试重新创建下面的 cURL 请求,但我的代码从服务器返回了一个错误的请求。我很确定这与格式不佳有关,但我无法弄清楚我哪里出错了。
//This code returns the data back successfully
curl -H "Content-Type: application/json" -d '{"bio_ids": ["1234567"]}' http://localhost:9292/program
<?php //This code returns a bad request from the server
$bio = array('bio_ids'=>'1234567');
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'http://localhost:9292/program',
CURLOPT_POST => 1, // -d
CURLOPT_POSTFIELDS => $bio,
CURLOPT_HTTPHEADER => array('Content-Type: application/json'), // -H
));
$resp = curl_exec($curl);
curl_close($curl);
?>
有两个问题:
您需要确保 $bio
的结构与您期望传递的结构相匹配,因此$bio
声明需要:
$bio = array('bio_ids' => array('1234567'));
其次,您需要在将数据发送到服务器之前json_encode
此数据结构:
CURLOPT_POSTFIELDS => json_encode($bio),
<?php //This code returns a bad request from the server
$bio = array('bio_ids'=>'1234567');
$bio = json_encode($bio);
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'http://localhost:9292/program',
CURLOPT_POST => 1, // -d
CURLOPT_POSTFIELDS => $bio,
CURLOPT_HTTPHEADER => array('Content-Type: application/json'), // -H
));
$resp = curl_exec($curl);
curl_close($curl);
?>