curl post json格式数据
function curlPost($url, $data = array())
{
$data = array("name" => "TEST", "age" => "20");
$data_string = json_encode($data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS,$data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
$output = curl_exec($ch);
curl_close($ch);
return $output;
}
数据接受方:(使用$_POST获取不到)
$req = file_get_contents("php://input"); // string
$arr = json_decode($req,true);
print_r($arr);
$arr = $_POST;// arr 为空数组
post application/x-www-form-urlencoded数据
function httpPost()
{
$url = '';
$data = array();
$headers = array();
$headers[] = "headdata1: 123";
$headers[] = "headdata2: 456";
$headers[] = "Content-Type: application/x-www-form-urlencoded"; // 可不填
$post_data = $data;
$post_data = http_build_query($post_data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$ret = curl_exec($ch);
curl_close($ch);
return $ret;
}
数据接受方:(使用$_POST获取不到)
$arr = $_POST;
print_r($arr);
curl GET:
function httpGET($url)
{
//初始化
$curl = curl_init();
//设置抓取的url
curl_setopt($curl, CURLOPT_URL, $url);
//设置头文件的信息作为数据流输出
curl_setopt($curl, CURLOPT_HEADER, true);
//设置获取的信息以文件流的形式返回,而不是直接输出。
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
//执行命令
$ret = curl_exec($curl);
//关闭URL请求
curl_close($curl);
return $ret;
}