php设置header body,curl 设置请求头headers和请求体body

直接贴代码:$url = "http://www.example.com";

//headers数组内的格式

$headers = array();

$headers[] = "app-id:xxxxx";

$headers[] = "Content-Type:application/json";

$body   = array(

"username" => "username",

"password" => "password"

);

$postBody    = json_encode($body);

$curl = curl_init();

curl_setopt($curl, CURLOPT_URL, $url);

curl_setopt($curl, CURLOPT_POST, true);

curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);//设置请求头

curl_setopt($curl, CURLOPT_POSTFIELDS, $postBody);//设置请求体

curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'POST');//使用一个自定义的请求信息来代替"GET"或"HEAD"作为HTTP请求。(这个加不加没啥影响)

$data = curl_exec($curl);

echo $data;