您好我将带有cURL的JSON数组发布到我的API
JSONData='
{
"customerCode": "DUMMY",
"fromLocation": {
"suburbName": "MELBOURNE",
"postCode": "3000",
"state": "VIC"
},
"toLocation": {
"suburbName": "SYDNEY",
"postCode": "2000",
"state": "NSW"
},
"goods": [
{
"pieces": "2",
"weight": "3",
"width": "10",
"height": "20",
"depth": "12",
"typeCode": "ENV"
}
]
} ';
我正在使用此代码传递数组,但它不起作用
$data_string = stripslashes($JSONData);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string)
));
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, array('JSONData'=>$data_string)
);
请帮我传递JSON数组。
答案 0 :(得分:0)
由于您将内容类型指定为application/json
,因此您必须json_encode
完整数据。所以试试吧,
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(array('JSONData'=>$data_string));
作为旁注,您还可以将curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
替换为curl_setopt($ch, CURLOPT_POST, "TRUE");
。
答案 1 :(得分:0)
$username='xxx';
$password='xxx';
$url='http://apiurl';
$opts = array('http' =>
array(
'method' => 'POST',
'header' => array('Content-type: application/json', 'Authorization: Basic '.base64_encode($username.':'.$password)),
'content' => $JSONData
)
);
$context = stream_context_create($opts);
$response = file_get_contents($url, false, $context);
echo 'response: '.$response;