我有下面的页面。
页面json.php
:
$json_data = array(
'first_name' => 'John',
'last_name' => 'Doe',
'birthdate' => '12/02/1977',
'files' => array(
array(
'name' => 'file1.zip',
'status' => 'good'
),
array(
'name' => 'file2.zip',
'status' => 'good'
)
)
);
$url = 'http://localhost/test.php';
$content = json_encode($json_data);
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER,
array(
"Content-type: application/json",
"Content-Length: " . strlen($content)
)
);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, 'json=' . urlencode($content));
curl_setopt($curl, CURLINFO_HEADER_OUT, true);
$json_response = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
$header_sent = curl_getinfo($curl, CURLINFO_HEADER_OUT);
curl_close($curl);
echo $header_sent;
echo '<br>';
echo $status;
echo '<br>';
echo $json_response;
页面test.php
:
echo '<pre>';
print_r($_POST);
echo '</pre>';
当我从浏览器调用 json.php 时,我得到以下结果:
POST /json.php HTTP/1.1 Host: localhost Accept: */* Content-type: application/json Content-Length: 150
200
Array
(
)
为什么我看不到我要发送的 POST 字符串?
编辑:
如果我不设置Content-type: application/json
标题(根据@landons 的评论),我会得到以下结果:
POST /ddabvd/widendcm/widendcm-finished.php HTTP/1.1 Host: localhost Accept: */* Content-Length: 150 Content-Type: application/x-www-form-urlencoded
200
Array
(
[json] => {"first_name":"John","last_name":"Doe","birthdate":"12\/02\/1977","files":[{"name":
)