### 我需要用curl以json格式请求,
curl_setopt($ch,CURLOPT_HTTPHEADER,[]); /*开始我设置成了关联数组,所以一直报错,仔细看文档,应该是索引数据[‘content-type:application/json‘]
CURLOPT_POSTFIELDS的数组类型应该用json_encode转一下,不然接口接收不到。
/*
*curl post
*Content-Type:application/json
*var $url string
*var $postData array
*/
function curl_post($url,$postData){
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch,CURLOPT_HEADER,true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch,CURLOPT_POST, true);
curl_setopt($ch,CURLOPT_POSTFIELDS,json_encode($postData));
curl_setopt($ch,CURLOPT_HTTPHEADER,[
‘Content-Type:application/json‘,
‘Connection:Keep-Alive‘
]);
$output = curl_exec($ch);
$response = array();
$errorCode = curl_errno($ch);
if ($errorCode) {
return false;
} else {
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$header_text = substr($output, 0, $header_size);
$body = substr($output, $header_size);
$headers = array();
foreach (explode("\r\n", $header_text) as $i => $line) {
if (!empty($line)) {
if ($i === 0) {
$headers[‘http_code‘] = $line;
} else if (strpos($line, ": ")) {
list ($key, $value) = explode(‘: ‘, $line);
$headers[$key] = $value;
}
}
}
$response[‘headers‘] = $headers;
$response[‘body‘] = $body;
$response[‘http_code‘] = $httpCode;
}
curl_close($ch);
return $response;
}