【发布时间】:2018-01-26 13:41:24
【问题描述】:
我认为这个问题是由于我对 PHP 中的数组缺乏了解。
通常我尝试使用 curl 在 php 中发送发布请求,但是我希望 postbody 看起来像这样:
{
"deliveryAddress":[
{
"ID":"5",
"address":"example@example2.com",
"method":"EMAIL",
"checkbox":true,
"flashlight":false
},
{
"ID":"7",
"address":"example45@example3.com",
"method":"EMAIL",
"checkbox":true,
"flashlight":false
}
]
}
大概是它在 API 中的样子,所以如果我把它放到像 Fiddler 这样的程序中,它工作得非常好。然而,把它变成 PHP 中的 postbody 我有更多的困难。这是我迄今为止最好的尝试:
$postData = array(
'deliveryAddress' => array(
'ID'=> '5',
'address'=> 'example@example2.com',
'method'=> 'EMAIL',
'checkbox'=> true,
'flashlight'=> false,
'ID'=> '7',
'address'=> 'example45@example3.com',
'method'=> 'EMAIL',
'checkbox'=> true,
'flashlight'=> false,
)
);
$url = "ServerIamSendingItTo";
$ch = curl_init();
$headers = array(
'Content-Type: application/json',
'Authorization: BASIC (mybase64encodedpass)=='
);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
//curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postData));
curl_setopt($ch, CURLOPT_URL, $url);
$result = curl_exec($ch);
$ch_error = curl_error($ch);
if ($ch_error) {
echo"ERROR";
curl_close($ch);
} else {
var_dump($result);
}
curl_close($ch);
显然我做错了 postdata,但我不确定如何构建它。任何帮助都会很棒。谢谢。
【问题讨论】:
-
你想要json,所以使用json_encode函数
-
@moped 我正在使用 json_encode 函数。 'curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postData));'